import { world } from "@minecraft/server";
import { ModalFormData } from "@minecraft/server-ui";

const scoreboardName = "settings";
const settingPlayers = {
    blockParticles: "blockParticles",
    ambientFog: "ambientFog",
    islandFog: "islandFog",
    islandClouds: "islandClouds",
    creakingEyes: "creakingEyes" // New setting
};

// Helper to get scoreboard value (fake player)
function getSetting(setting) {
    try {
        return world.scoreboard.getObjective(scoreboardName).getScore(setting) === 1;
    } catch {
        return false; // Default to false if not set
    }
}

// Helper to set scoreboard value (fake player)
function setSetting(setting, value) {
    let objective = world.scoreboard.getObjective(scoreboardName);
    if (!objective) objective = world.scoreboard.addObjective(scoreboardName, scoreboardName);
    objective.setScore(setting, value ? 1 : 0);
}

const Settings = {
    onUse({ source }) {
        const player = source;

        // Current scoreboard settings
        const blockParticles = getSetting(settingPlayers.blockParticles);
        const ambientFog = getSetting(settingPlayers.ambientFog);
        const islandFog = getSetting(settingPlayers.islandFog);
        const islandClouds = getSetting(settingPlayers.islandClouds);
        const creakingEyes = getSetting(settingPlayers.creakingEyes); // Fetch value

        let form = new ModalFormData()
            .title("VFX Settings")
            .toggle("Block Particles", blockParticles)
            .toggle("Ambient Fog", ambientFog)
            .toggle("Island Fog", islandFog)
            .toggle("Island Clouds", islandClouds)
            .toggle("Creaking Eyes", creakingEyes); // New toggle

        form.show(player).then((r) => {
            if (r.canceled) return;

            let [newBlock, newAmbient, newIslandFog, newIslandClouds, newCreakingEyes] = r.formValues;

            if (blockParticles !== newBlock) setSetting(settingPlayers.blockParticles, newBlock);
            if (ambientFog !== newAmbient) setSetting(settingPlayers.ambientFog, newAmbient);
            if (islandFog !== newIslandFog) setSetting(settingPlayers.islandFog, newIslandFog);
            if (islandClouds !== newIslandClouds) setSetting(settingPlayers.islandClouds, newIslandClouds);
            if (creakingEyes !== newCreakingEyes) setSetting(settingPlayers.creakingEyes, newCreakingEyes); // Save new value
        }).catch((e) => {
            console.error(e, e.stack);
        });
    }
};

world.beforeEvents.worldInitialize.subscribe(e => {
    e.itemComponentRegistry.registerCustomComponent("gs_ce:settings", Settings);
});
