function getAssetUrl(path) {
    const cleanPath = path.replace(/^\.\//, '');
    if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.getURL) {
        return chrome.runtime.getURL(cleanPath);
    }
    return path;
}

document.addEventListener('DOMContentLoaded', function() {
    const assetsBaseUrl = typeof chrome !== 'undefined' && chrome.runtime ? chrome.runtime.getURL('assets/') : './assets/';
    
    const styleSheets = document.styleSheets;
    for (let sheet of styleSheets) {
        try {
            const rules = sheet.cssRules || sheet.rules;
            for (let rule of rules) {
                if (rule.style && rule.style.backgroundImage) {
                    rule.style.backgroundImage = rule.style.backgroundImage.replace(/\.\/assets\//g, assetsBaseUrl);
                }
            }
        } catch (e) {
            console.error("An error occurred while updating the CSS background images:", e);
        }
    }
});

var editing = false;
var isMoving = false;
var is_creating_new_loadout = false;
var original_loadout_name = null;

var loadouts = [];

const loadout_selector = document.getElementById("select-loadout");
const load_loadout_button = document.getElementById("load-loadout");
const edit_loadout_button = document.getElementById("edit-loadout");
const create_loadout_button = document.getElementById("create-loadout");
const delete_loadout_button = document.getElementById("delete-loadout");
const delete_loadout = document.getElementById("delete-loadout-overlay");
const delete_loadout_name = document.getElementById("delete-loadout-name");
const loadout_selector_container = document.getElementById("loadout-selector-container");
const loadout_button_container = document.getElementById("loadout-button-container");
const loadout_edit_container = document.getElementById("loadout-edit-container");
const loadout_name_input = document.getElementById("loadout-name-input");
const save_loadout_button = document.getElementById("save-loadout-button");
const cancel_loadout_button = document.getElementById("cancel-loadout-button");

const export_loadout_button = document.getElementById("export-loadout");
const import_loadout_button = document.getElementById("import-loadout");

const soul_1 = document.getElementById("soul-1");
const soul_2 = document.getElementById("soul-2");
const soul_3 = document.getElementById("soul-3");
const soul_4 = document.getElementById("soul-4");
const soul_5 = document.getElementById("soul-5");
const soul_6 = document.getElementById("soul-6");
const soul_7 = document.getElementById("soul-7");
const soul_8 = document.getElementById("soul-8");

const soul_level_1 = document.getElementById("soul-level-1");
const soul_level_2 = document.getElementById("soul-level-2");
const soul_level_3 = document.getElementById("soul-level-3");
const soul_level_4 = document.getElementById("soul-level-4");
const soul_level_5 = document.getElementById("soul-level-5");
const soul_level_6 = document.getElementById("soul-level-6");
const soul_level_7 = document.getElementById("soul-level-7");
const soul_level_8 = document.getElementById("soul-level-8");

const soul_level_inputs = [soul_level_1, soul_level_2, soul_level_3, soul_level_4, soul_level_5, soul_level_6, soul_level_7, soul_level_8];

const show_gem_cost_checkbox = document.getElementById("show-gem-cost-checkbox");

let active_loadout = null;

function loadGemCostSetting() {
    const saved = localStorage.getItem('showGemCost');
    if (saved !== null) {
        show_gem_cost_checkbox.checked = saved === 'true';
    } else {
        show_gem_cost_checkbox.checked = true;
        localStorage.setItem('showGemCost', 'true');
    }
}

function saveGemCostSetting() {
    localStorage.setItem('showGemCost', show_gem_cost_checkbox.checked.toString());
    if (typeof window !== 'undefined') {
        window.__showGemCost = show_gem_cost_checkbox.checked;
    }
}

function getShowGemCost() {
    const saved = localStorage.getItem('showGemCost');
    return saved === null ? true : saved === 'true';
}

function updateSoulArrows() {
    for (let i = 1; i <= 8; i++) {
        const upButton = document.getElementById(`soul-up-${i}`);
        const downButton = document.getElementById(`soul-down-${i}`);
        const input = soul_level_inputs[i - 1];
        
        if (upButton && downButton && input) {
            if (editing) {
                upButton.disabled = false;
                downButton.disabled = false;
            } else {
                upButton.disabled = true;
                downButton.disabled = true;
            }
        }
    }
}

function setupSoulArrows() {
    for (let i = 1; i <= 8; i++) {
        const upButton = document.getElementById(`soul-up-${i}`);
        const downButton = document.getElementById(`soul-down-${i}`);
        const input = soul_level_inputs[i - 1];
        
        if (upButton && input) {
            upButton.addEventListener('click', function() {
                if (!editing) return;
                let currentValue = parseInt(input.value) || 1;
                if (currentValue < 99) {
                    input.value = currentValue + 1;
                }
            });
        }
        
        if (downButton && input) {
            downButton.addEventListener('click', function() {
                if (!editing) return;
                let currentValue = parseInt(input.value) || 1;
                if (currentValue > 1) {
                    input.value = currentValue - 1;
                }
            });
        }
    }
}

function updateLoadoutSelector() {
    try {
        const savedLoadouts = localStorage.getItem('ZSouls');
        if (savedLoadouts) {
            try {
                loadouts = JSON.parse(savedLoadouts);
            } catch (e) {
                console.error("Error parsing saved loadouts:", e);
                loadouts = [];
            }
        } else {
            loadouts = [];
        }
        
        if (!loadout_selector) {
            console.error("loadout_selector not found");
            return;
        }
        
        loadout_selector.innerHTML = "";
        if (loadouts.length > 0) {
            loadouts.forEach(l => {
                const option = document.createElement("option");
                option.value = l.name;
                option.textContent = l.name;
                loadout_selector.appendChild(option);
            });
            
            const savedActive = localStorage.getItem('active_loadout');
            if (savedActive && loadouts.find(l => l.name === savedActive)) {
                active_loadout = savedActive;
            } else {
                active_loadout = loadouts[0].name;
                localStorage.setItem('active_loadout', active_loadout);
            }
            
            loadout_selector.value = active_loadout;
            
            if (loadout_selector) loadout_selector.disabled = false;
            if (edit_loadout_button) edit_loadout_button.disabled = false;
            if (delete_loadout_button) delete_loadout_button.disabled = false;
            if (load_loadout_button) load_loadout_button.disabled = false;
            if (export_loadout_button) export_loadout_button.disabled = false;
        } else {
            active_loadout = null;
            loadout_selector.innerHTML = "<option>No loadouts found - Create one!</option>";
            if (loadout_selector) loadout_selector.disabled = true;
            if (edit_loadout_button) edit_loadout_button.disabled = true;
            if (delete_loadout_button) delete_loadout_button.disabled = true;
            if (load_loadout_button) load_loadout_button.disabled = true;
            if (export_loadout_button) export_loadout_button.disabled = true;
        }
        if (create_loadout_button) create_loadout_button.disabled = false;
        updateVisual();
    } catch (error) {
        console.error("Error in updateLoadoutSelector:", error);
    }
}

function editLoadout() {
    try {
        if (!loadout_selector || !loadout_selector.value || loadout_selector.disabled) {
            return;
        }
        active_loadout = loadout_selector.value;
        let loadout = loadouts.find(l => l.name === active_loadout);
        if (!loadout) {
            alert("Loadout not found");
            return;
        }
        editing = true;
        original_loadout_name = active_loadout;
        localStorage.setItem('active_loadout', active_loadout);
        
        if (loadout_selector_container) loadout_selector_container.style.display = 'none';
        if (loadout_button_container) loadout_button_container.style.display = 'none';
        if (loadout_edit_container) loadout_edit_container.style.display = 'block';
        if (loadout_name_input) {
            loadout_name_input.value = active_loadout;
            loadout_name_input.focus();
            loadout_name_input.select();
        }
        
        soul_level_inputs.forEach(input => {
            if (input) input.disabled = false;
        });
        
        updateSoulArrows();
        updateVisual();
    } catch (error) {
        console.error("Error in editLoadout:", error);
        alert("Error editing loadout: " + error.message);
    }
}

function createNewLoadout() {
    try {
        is_creating_new_loadout = true;
        active_loadout = null;
        editing = true;
        
        if (loadout_selector_container) loadout_selector_container.style.display = 'none';
        if (loadout_button_container) loadout_button_container.style.display = 'none';
        if (loadout_edit_container) loadout_edit_container.style.display = 'block';
        if (loadout_name_input) {
            loadout_name_input.value = "";
            loadout_name_input.focus();
        }
        
        soul_level_inputs.forEach(input => {
            if (input) input.disabled = false;
        });
        
        updateSoulArrows();
        updateVisual();
    } catch (error) {
        console.error("Error in createNewLoadout:", error);
        alert("Error creating loadout: " + error.message);
    }
}

function saveLoadout() {
    try {
        let loadoutName = loadout_name_input ? loadout_name_input.value.trim() : "";
        if (!loadoutName) {
            alert("Please enter a loadout name");
            if (loadout_name_input) loadout_name_input.focus();
            return;
        }

        if (!is_creating_new_loadout && loadoutName !== original_loadout_name) {
            loadouts = loadouts.filter(l => l.name !== original_loadout_name);
        }

        loadouts = loadouts.filter(l => l.name !== loadoutName);

        const soul_levels = [
            parseInt(soul_level_1.value) || 1,
            parseInt(soul_level_2.value) || 1,
            parseInt(soul_level_3.value) || 1,
            parseInt(soul_level_4.value) || 1,
            parseInt(soul_level_5.value) || 1,
            parseInt(soul_level_6.value) || 1,
            parseInt(soul_level_7.value) || 1,
            parseInt(soul_level_8.value) || 1
        ];

        loadouts.push({
            name: loadoutName,
            soul_levels
        });

        active_loadout = loadoutName;
        localStorage.setItem('ZSouls', JSON.stringify(loadouts));
        localStorage.setItem('active_loadout', active_loadout);

        editing = false;
        is_creating_new_loadout = false;
        
        if (loadout_edit_container) loadout_edit_container.style.display = 'none';
        if (loadout_selector_container) loadout_selector_container.style.display = 'flex';
        if (loadout_button_container) loadout_button_container.style.display = 'flex';
        
        soul_level_inputs.forEach(input => {
            if (input) input.disabled = true;
        });
        
        updateSoulArrows();
        updateLoadoutSelector();
        updateVisual();
    } catch (error) {
        console.error("Error in saveLoadout:", error);
        alert("Error saving loadout: " + error.message);
    }
}

function cancelLoadout() {
    try {
        editing = false;
        is_creating_new_loadout = false;
        
        // Hide edit interface, show normal interface
        if (loadout_edit_container) loadout_edit_container.style.display = 'none';
        if (loadout_selector_container) loadout_selector_container.style.display = 'flex';
        if (loadout_button_container) loadout_button_container.style.display = 'flex';
        
        // Disable soul level inputs
        soul_level_inputs.forEach(input => {
            if (input) input.disabled = true;
        });
        
        updateSoulArrows();
        updateSoulArrows();
        updateLoadoutSelector();
        updateVisual();
    } catch (error) {
        console.error("Error in cancelLoadout:", error);
    }
}

function loadLoadout() {
    try {
        const savedLoadouts = localStorage.getItem('ZSouls');
        const activeLoadoutName = localStorage.getItem('active_loadout');
        
        if (!savedLoadouts || !activeLoadoutName) {
            console.error("No active loadout found");
            return;
        }
        
        const loadouts = JSON.parse(savedLoadouts);
        const activeLoadout = loadouts.find(l => l.name === activeLoadoutName);
        
        if (!activeLoadout) {
            console.error("Active loadout not found in saved loadouts");
            return;
        }
        
        const jsUrl = chrome.runtime.getURL('scripts/loadLoadout.js');
        fetch(jsUrl)
            .then(response => response.text())
            .then(codeToInject => {
                if (codeToInject) {
                    const loadoutDataString = JSON.stringify(activeLoadout);
                    const showGemCost = getShowGemCost();
                    const codeWithData = codeToInject.replace(
                        'window.logLoadout = logLoadout;',
                        `window.__activeLoadoutData = ${loadoutDataString};\nwindow.__showGemCost = ${showGemCost};\nwindow.logLoadout = logLoadout;`
                    );
                    
                    chrome.runtime.sendMessage({
                        action: 'injectInterceptor',
                        code: codeWithData
                    }, (response) => {
                        if (response?.success) {
                            chrome.runtime.sendMessage({ action: 'executeFunction', func: 'logLoadout' });
                        } else {
                            console.error("Zynga's AIO Error:", response?.error);
                        }
                    });
                }
            })
            .catch(error => {
                console.error("Zynga's AIO Error:", error);
            });
    } catch (error) {
        console.error("Zynga's AIO Error:", error);
    }
}

function deleteLoadout() {
    try {
        if (!active_loadout) {
            if (loadout_selector && loadout_selector.value) {
                active_loadout = loadout_selector.value;
            } else {
                alert("Please select a loadout first");
                return;
            }
        }
        if (!delete_loadout || !delete_loadout_name) {
            console.error("Delete overlay elements not found");
            return;
        }
        delete_loadout.style.display = "block";
        delete_loadout_name.innerHTML = active_loadout;
    } catch (error) {
        console.error("Error in deleteLoadout:", error);
        alert("Error deleting loadout: " + error.message);
    }
}

function deleteLoadoutVerified() {
    active_loadout = delete_loadout_name.innerHTML;
    loadouts = loadouts.filter(l => l.name !== active_loadout);
    localStorage.setItem('ZSouls', JSON.stringify(loadouts));
    localStorage.removeItem('active_loadout');
    delete_loadout.style.display = "none";
    delete_loadout_name.innerHTML = "";
    active_loadout = loadouts.length > 0 ? loadouts[0].name : null;
    updateLoadoutSelector();
}

function cancelDelete() {
    if (delete_loadout) {
        delete_loadout.style.display = "none";
    }
    if (delete_loadout_name) {
        delete_loadout_name.innerHTML = "";
    }
}

function exportLoadout() {
    let loadout = loadouts.find(l => l.name === active_loadout);
    if (!loadout) {
        alert("No loadout selected");
        return;
    }
    
    const exportData = {
        n: loadout.name,
        s: loadout.soul_levels
    };
    
    let export_string = JSON.stringify(exportData);
    export_string = btoa(export_string);
    
    navigator.clipboard.writeText(export_string).then(() => {
        alert("Loadout copied to clipboard!");
    }).catch(err => {
        console.error("Failed to copy to clipboard:", err);
        const textarea = document.createElement("textarea");
        textarea.value = export_string;
        textarea.style.position = "fixed";
        textarea.style.opacity = "0";
        document.body.appendChild(textarea);
        textarea.select();
        try {
            document.execCommand('copy');
            alert("Loadout copied to clipboard!");
        } catch (e) {
            console.error("Failed to copy:", e);
            alert("Failed to copy to clipboard. String: " + export_string);
        }
        document.body.removeChild(textarea);
    });
}

function importLoadout() {
    const importString = prompt("Paste the loadout string:");
    if (!importString || !importString.trim()) {
        return;
    }
    
    try {
        const decoded = atob(importString.trim());
        const data = JSON.parse(decoded);
        
        if (!data.n || !data.s || !Array.isArray(data.s) || data.s.length !== 8) {
            alert("Invalid loadout string format");
            return;
        }
        
        let loadoutName = data.n + " [Imported]";
        
        let counter = 1;
        while (loadouts.find(l => l.name === loadoutName)) {
            loadoutName = data.n + " [Imported] (" + counter + ")";
            counter++;
        }
        
        const loadout = {
            name: loadoutName,
            soul_levels: data.s
        };
        
        loadouts.push(loadout);
        localStorage.setItem('ZSouls', JSON.stringify(loadouts));
        
        updateLoadoutSelector();
        updateVisual();
        
        alert("Loadout imported successfully!");
    } catch (e) {
        console.error("Error parsing loadout:", e);
        alert("Invalid loadout string. Please check the string and try again.");
    }
}

function updateVisual() {
    let loadout = null;
    if (is_creating_new_loadout && loadout_name_input) {
        let inputName = loadout_name_input.value.trim();
        if (inputName) {
            loadout = loadouts.find(l => l.name === inputName);
            if (!loadout) {
                loadout = {
                    name: inputName,
                    soul_levels: [1, 1, 1, 1, 1, 1, 1, 1]
                };
            }
        } else {
            loadout = {
                name: "",
                soul_levels: [1, 1, 1, 1, 1, 1, 1, 1]
            };
        }
    }
    if (!loadout) {
        if (active_loadout) {
            loadout = loadouts.find(l => l.name === active_loadout);
        }
        if (!loadout && loadouts.length > 0) {
            loadout = loadouts[0];
            active_loadout = loadouts[0].name;
            if (loadout_selector) {
                loadout_selector.value = active_loadout;
            }
            localStorage.setItem('active_loadout', active_loadout);
        }
        if (!loadout) {
            loadout = {
                name: "Default",
                soul_levels: [1, 1, 1, 1, 1, 1, 1, 1]
            };
        }
    }

    const soulImages = [
        './assets/souls/Blade_Duo.png',
        './assets/souls/Bloodstained_Blade.png',
        './assets/souls/Excellent_Companion.png',
        './assets/souls/Eye_of_the_Abyss.png',
        './assets/souls/Forgiving_Horns.png',
        './assets/souls/Guardian_Star.png',
        './assets/souls/Immortal_Spirit.png',
        './assets/souls/Wildfire_Piercer.png'
    ];
    
    const soulElements = [soul_1, soul_2, soul_3, soul_4, soul_5, soul_6, soul_7, soul_8];
    const soulLevelInputs = [soul_level_1, soul_level_2, soul_level_3, soul_level_4, soul_level_5, soul_level_6, soul_level_7, soul_level_8];
    
    soulElements.forEach((soul, index) => {
        if (!soul) return;
        
        if (editing) {
            soul.classList.add('editing');
        } else {
            soul.classList.remove('editing');
        }
        
        const existingImg = soul.querySelector('img');
        if (existingImg) {
            existingImg.src = getAssetUrl(soulImages[index]);
        } else {
            const img = document.createElement('img');
            img.src = getAssetUrl(soulImages[index]);
            img.style.width = '80%';
            img.style.height = '80%';
            img.style.objectFit = 'contain';
            const input = soul.querySelector('.soul-level-input');
            if (input) {
                soul.insertBefore(img, input);
            } else {
                soul.appendChild(img);
            }
        }
        
        const soulLevels = loadout.soul_levels || [1, 1, 1, 1, 1, 1, 1, 1];
        const level = soulLevels[index] !== undefined ? soulLevels[index] : 1;
        if (soulLevelInputs[index]) {
            soulLevelInputs[index].value = level;
            soulLevelInputs[index].disabled = !editing;
        }
    });
}

if (loadout_selector) {
    loadout_selector.onchange = function() {
        active_loadout = loadout_selector.value;
        localStorage.setItem('active_loadout', active_loadout);
        updateVisual();
    };
}

window.editLoadout = editLoadout;
window.createNewLoadout = createNewLoadout;
window.deleteLoadout = deleteLoadout;
window.loadLoadout = loadLoadout;
window.exportLoadout = exportLoadout;
window.importLoadout = importLoadout;
window.saveLoadout = saveLoadout;
window.cancelLoadout = cancelLoadout;
window.deleteLoadoutVerified = deleteLoadoutVerified;
window.cancelDelete = cancelDelete;
window.getShowGemCost = getShowGemCost;

if (show_gem_cost_checkbox) {
    loadGemCostSetting();
    show_gem_cost_checkbox.addEventListener('change', function() {
        saveGemCostSetting();
    });
}

if (edit_loadout_button) {
    edit_loadout_button.addEventListener('click', editLoadout);
}
if (create_loadout_button) {
    create_loadout_button.addEventListener('click', createNewLoadout);
}
if (delete_loadout_button) {
    delete_loadout_button.addEventListener('click', deleteLoadout);
}
if (load_loadout_button) {
    load_loadout_button.addEventListener('click', loadLoadout);
}
if (export_loadout_button) {
    export_loadout_button.addEventListener('click', exportLoadout);
}
if (import_loadout_button) {
    import_loadout_button.addEventListener('click', importLoadout);
}
if (save_loadout_button) {
    save_loadout_button.addEventListener('click', saveLoadout);
}
if (cancel_loadout_button) {
    cancel_loadout_button.addEventListener('click', cancelLoadout);
}

const yes_button = document.getElementById('yes-button');
const no_button = document.getElementById('no-button');
if (yes_button) {
    yes_button.addEventListener('click', deleteLoadoutVerified);
}
if (no_button) {
    no_button.addEventListener('click', cancelDelete);
}

if (loadout_name_input) {
    loadout_name_input.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            saveLoadout();
        }
    });
    
    loadout_name_input.addEventListener('input', function() {
        if (is_creating_new_loadout) {
            updateVisual();
        }
    });
}

function setupSoulClickHandlers() {
    const souls = [soul_1, soul_2, soul_3, soul_4, soul_5, soul_6, soul_7, soul_8];
    
    souls.forEach((soul, index) => {
        if (soul && soul_level_inputs[index]) {
            soul.addEventListener('click', function() {
                if (editing && !soul_level_inputs[index].disabled) {
                    soul_level_inputs[index].focus();
                    soul_level_inputs[index].select();
                }
            });
        }
    });
}

function initializeApp() {
    try {
        setupSoulArrows();
        setupSoulClickHandlers();
        updateSoulArrows();
        
        if (show_gem_cost_checkbox) {
            loadGemCostSetting();
        }
        
        const savedLoadouts = localStorage.getItem('ZSouls');
        if (savedLoadouts) {
            try {
                loadouts = JSON.parse(savedLoadouts);
            } catch (e) {
                console.error("Error parsing saved loadouts:", e);
                loadouts = [];
            }
        } else {
            loadouts = [];
        }
        
        if (loadout_selector) {
            updateLoadoutSelector();
        } else {
            updateVisual();
        }
        
        setTimeout(function() {
            if (loadouts.length > 0 && !active_loadout) {
                active_loadout = loadouts[0].name;
                if (loadout_selector) {
                    loadout_selector.value = active_loadout;
                }
                localStorage.setItem('active_loadout', active_loadout);
            }
            updateVisual();
        }, 100);
    } catch (error) {
        console.error("Error during initialization:", error);
        setTimeout(initializeApp, 100);
    }
}

(function() {
    function runInit() {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function() {
                initializeApp();
            });
        } else {
            setTimeout(function() {
                initializeApp();
            }, 100);
        }
    }
    
    runInit();
    
    window.addEventListener('load', function() {
        if (!active_loadout && loadouts.length > 0) {
            initializeApp();
        }
    });

    window.addEventListener('mousedown', (e) => {
        const target = e.target;
        const isInteractive = target.tagName === 'BUTTON' || 
                             target.tagName === 'INPUT' || 
                             target.tagName === 'SELECT' || 
                             target.closest('button') || 
                             target.closest('input') || 
                             target.closest('select') ||
                             target.closest('.soul') ||
                             target.closest('.soul-arrow-button') ||
                             target.closest('.soul-arrows');
        
        if (isInteractive) {
            return;
        }
        
        window.parent.postMessage({'type': 'mousedown', data: {x: e.clientX, y: e.clientY}}, '*');
        e.preventDefault();
        e.stopPropagation();
        isMoving = true;
    });
})();
