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

const scoreboardName = "settings";
const settingPlayers = {
    blockParticles: "blockParticles",
    ambientFog: "ambientFog",
    islandFog: "islandFog",
    islandClouds: "islandClouds"
};

// 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);

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

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

            let [newBlock, newAmbient, newIslandFog, newIslandClouds] = 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);
        }).catch((e) => {
            console.error(e, e.stack);
        });
    }
};

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