import { world, system } from "@minecraft/server";

const COLOR_OBJECTIVES = [
    { name: "red", id: 0 },
    { name: "cyan", id: 1 },
    { name: "hole", id: 2 },
    { name: "pink", id: 3 },
    { name: "black", id: 4 }
];

// --- Night type selection (forced or random) ---
system.afterEvents.scriptEventReceive.subscribe((event) => {
    if (event.id !== "aria_ah:random_night") return;

    const nightObj = world.scoreboard.getObjective("aria_ah.night");
    if (!nightObj) return;

    // Check for a direct night type parameter
    let param = event.message?.trim();
    if (param !== undefined && param !== "") {
        let forcedType = parseInt(param, 10);
        if (!isNaN(forcedType) && forcedType >= 0 && forcedType <= 4) {
            nightObj.setScore("type", forcedType);
            return;
        }
    }

    // Get weights for each color from the fake player scores
    const scores = COLOR_OBJECTIVES.map(color => {
        return nightObj.getScore(color.name) ?? 0;
    });

    const totalWeight = scores.reduce((sum, weight) => sum + weight, 0);
    if (totalWeight === 0) return;

    let random = Math.random() * totalWeight;
    let selectedId = 0;

    for (let i = 0; i < scores.length; i++) {
        random -= scores[i];
        if (random < 0) {
            selectedId = COLOR_OBJECTIVES[i].id;
            break;
        }
    }

    // Write the result (0-4) to the "type" fake player in aria_ah.night
    nightObj.setScore("type", selectedId);
});

// --- Nightfall/time tracking and event trigger ---
let previousType = -1;

system.run(function tick() {
    system.runTimeout(() => tick(), 10);

    const daytime = world.getTimeOfDay();
    const generalObj = world.scoreboard.getObjective("aria_ah.general") || 
                      world.scoreboard.addObjective("aria_ah.general", "General Status");
    const nightObj = world.scoreboard.getObjective("aria_ah.night");

    generalObj.setScore("time", daytime);
    const NIGHT_START = 13188;
    const NIGHT_END = 22813;
    const EVENT_END_EXTENDED = NIGHT_END + 300;

    const isNight = daytime >= NIGHT_START && daytime <= NIGHT_END;
    generalObj.setScore("nightfall", isNight ? 1 : 0);

    const isEventTime = daytime <= NIGHT_START || daytime >= EVENT_END_EXTENDED;
    
    if (isEventTime && nightObj) {
        const currentType = nightObj.getScore("type") ?? -1;
        if (currentType !== previousType && currentType >= 0) {
            world.getDimension("overworld").runCommand(
                `scriptevent aria_ah:moon_type ${currentType}`
            );
            previousType = currentType;
        }
    } else {
        previousType = -1;
    }
});

// --- Night sound scheduling ---
let soundQueue = [];

system.afterEvents.scriptEventReceive.subscribe((event) => {
    if (event.id !== "aria_ah:night_sound") return;

    const nightObj = world.scoreboard.getObjective("aria_ah.night");
    if (!nightObj) {
        //world.sendMessage("[DEBUG] No 'aria_ah.night' objective found.");
        return;
    }

    const soundType = nightObj.getScore("type") ?? -1;
    //world.sendMessage(`[DEBUG] Sound type is ${soundType}`);

    const SOUND_CONFIG = {
        0: [
            { name: "aria_ah.nightfall_alarm_short", duration: 7 },
            { name: "aria_ah.nightfall_alarm_short", duration: 7 },
            { name: "aria_ah.nightfall_alarm_long", duration: 9 }
        ],
        1: [
            { name: "aria_ah.nightfall_alarm_short", duration: 7 }
        ],
        2: [
            { name: "aria_ah.blackhole_alarm", duration: 4 },
            { name: "aria_ah.blackhole_alarm", duration: 4 },
            { name: "aria_ah.blackhole_alarm", duration: 4 }
        ],
        3: [
            { name: "aria_ah.title_hit", duration: 1.5 }
        ],
        4: [
            { name: "aria_ah.nightfall_alarm_short", duration: 7 },
            { name: "aria_ah.nightfall_alarm_long", duration: 7 }
        ]
    };

    if (!SOUND_CONFIG[soundType]) {
        //world.sendMessage(`[DEBUG] No sound config for type ${soundType}`);
        return;
    }

    // Clear any existing scheduled sounds
    soundQueue.forEach(timeoutId => system.clearRun(timeoutId));
    soundQueue = [];

    let totalDelay = 0;
    SOUND_CONFIG[soundType].forEach((sound, index) => {
        //world.sendMessage(`[DEBUG] Scheduling '${sound.name}' at +${(totalDelay/20).toFixed(2)}s`);
        let timeoutId = system.runTimeout(() => {
            //world.sendMessage(`§a[DEBUG] Playing sound: ${sound.name}`);
            world.getDimension("overworld").runCommand(
                `execute at @a as @a run playsound ${sound.name} @s ~ ~ ~ 1 1`
            );
        }, totalDelay);
        soundQueue.push(timeoutId);

        if (index < SOUND_CONFIG[soundType].length - 1) {
            totalDelay += (sound.duration - 0.5) * 20; // 0.5s overlap, convert to ticks
        }
    });
});
