import { world, system, MolangVariableMap } from "@minecraft/server";
import { settingEnabled } from "../settings"; // Import the function to check settings

// Constants
const godrayDelayTicks = 200;
const godrayParticles = [
    { name: "squaredreams_realism:godray_1", time: 3000, tolerance: 300 },
    { name: "squaredreams_realism:godray_2", time: 6000, tolerance: 300 },
    { name: "squaredreams_realism:godray_3", time: 9000, tolerance: 300 }
];

// Function to get a random element from an array
function getRandomElement(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}

// Main loop to check all players at regular intervals
system.runInterval(() => {
    // Check if the godrays setting is enabled
    const godraysEnabled = settingEnabled("godrays");

    // If not enabled, return
    if (!godraysEnabled) return;

    const overworld = world.getDimension("overworld");
    const absoluteTime = world.getAbsoluteTime();
    const timeOfDay = absoluteTime % 24000;

    overworld.getPlayers().forEach(player => {
        if (!player.isValid()) return;

        godrayParticles.forEach(particle => {
            if (timeOfDay >= (particle.time - particle.tolerance) && timeOfDay <= (particle.time + particle.tolerance)) {
                const randomOffset = {
                    x: (Math.random() - 0.5) * 20,
                    y: (Math.random() - 0.5) * 1,
                    z: (Math.random() - 0.5) * 20
                };
                const spawnPosition = {
                    x: player.location.x + randomOffset.x,
                    y: player.location.y + randomOffset.y,
                    z: player.location.z + randomOffset.z
                };

                overworld.spawnParticle(particle.name, spawnPosition, new MolangVariableMap());
            }
        });
    });
}, godrayDelayTicks);