import { world, system } from "@minecraft/server";
import { startHordeNight, endHordeNight } from "./Zombified/horde_logic.js"; // Import Horde logic
import { toggleHordeEffects, clearAllEffects } from "./Zombified/horde_effects.js"; // Import Horde effects
import "./Zombified/CustomEvents/index.js"; // Import event listener
import "./Zombified/entity_events.js"; // Import event listener
import "./Zombified/debug_events.js"; // Import event listener
import "./Zombified/vfx.js"; // Import event listener



world.afterEvents.playerSpawn.subscribe((e) => {
    const player = e.player;

    // On initial spawn, give menu
    if (e.initialSpawn === true && !player.hasTag('zombified_spawned')) {
        player.runCommand(`loot spawn ~~~ loot "lv_zo/menu"`);
        player.addTag('zombified_spawned');
    }

    const isHordeNightActive = getScore("horde_active") === 1;

    // Ensure effects match global horde night status
    if (isHordeNightActive) {
        // Apply effects if horde is currently active
        toggleHordeEffects(true);
    } else {
        // Clear them in case player still has them from disconnecting during a past horde
        toggleHordeEffects(false);
    }
});


// Define a fake player name for score tracking
const scoreboardHolder = "lv_zo_global_tracker";
const scoreboardName = "lv_zo_global_toggles";
let lastCheckedTime = world.getTimeOfDay();

let daysUntilHorde = 7; // default fallback
try {
    const objective = world.scoreboard.getObjective(scoreboardName);
    const participant = objective?.getParticipants().find(p => p.displayName === "slider_horde_night_interval");

    if (participant) {
        const score = objective.getScore(participant);
        if (typeof score === "number" && !isNaN(score)) {
            daysUntilHorde = score;
        }
    }
} catch (err) {
    console.warn("Failed to read slider_horde_night_interval:", err);
}


// Handle player join events
world.afterEvents.playerJoin.subscribe((event) => {
    const isHordeNightActive = getScore("horde_active") === 1;

    if (isHordeNightActive) {
        startHordeNight(); // Ensure Horde Night resumes
    }
});

// Setup scoreboards
function setupScoreboards() {
    if (!world.scoreboard.getObjective("days_survived")) {
        world.scoreboard.addObjective("days_survived", "Days Survived");
    }
    if (!world.scoreboard.getObjective("horde_active")) {
        world.scoreboard.addObjective("horde_active", "Horde Active");
    }

    // Initialize the global tracker if not present
    if (!world.scoreboard.getObjective("days_survived").getParticipants().some(p => p.displayName === scoreboardHolder)) {
        setScore("days_survived", world.getDay());
    }
    if (!world.scoreboard.getObjective("horde_active").getParticipants().some(p => p.displayName === scoreboardHolder)) {
        setScore("horde_active", 0);
    }
}
setupScoreboards();
toggleHordeEffects(getScore("horde_active"));


// Function to get a score from the scoreboard
function getScore(objectiveName) {
    let objective = world.scoreboard.getObjective(objectiveName);
    if (!objective) return 0;

    let participant = objective.getParticipants().find(p => p.displayName === scoreboardHolder);
    return participant ? objective.getScore(participant) : 0;
}

// Function to set a score on the scoreboard
function setScore(objectiveName, value) {
    let objective = world.scoreboard.getObjective(objectiveName);
    if (objective) {
        objective.setScore(scoreboardHolder, value);
    }
}

// Main Loop
system.runInterval(() => {
    const currentTime = world.getTimeOfDay();
    const daysSurvived = getScore("days_survived") || world.getDay();
    const isHordeNightActive = getScore("horde_active") === 1;

    if (isHordeNightActive && currentTime < 16000) {
        console.warn("[ZOMBIFIED] Detected time skip during Horde Night. Forcing end...");
        setScore("horde_active", 0);
        endHordeNight();
        clearAllEffects(true);
        return;
    }

    // Day tracking
    if (currentTime < lastCheckedTime && currentTime < 1000) {
        setScore("days_survived", daysSurvived + 1);
        const newDaysSurvived = daysSurvived + 1;
        const daysUntilNextHorde = daysUntilHorde - (newDaysSurvived % daysUntilHorde);

        if (daysUntilNextHorde > 0 && daysUntilNextHorde < 4) {
            world.sendMessage(`§8[§2ZOMBIFIED§8]§r Next §c§lHorde Night§r in ${daysUntilNextHorde} day(s)!`);
        }

        if (newDaysSurvived % daysUntilHorde === 0 && daysSurvived > 0) {
            world.sendMessage("§8[§2ZOMBIFIED§8]§r Tonight is a §c§lHorde Night§r! Prepare yourself!");
            for (const player of world.getPlayers()) {
                player.runCommandAsync('playsound lv_zo.horde_night.notification @s ~~~ 0.6');
            }
        }
    }

    // Start Horde Night at 16,000
    if (!isHordeNightActive && currentTime >= 16000 && currentTime < 23000 && (daysSurvived % daysUntilHorde === 0 && daysSurvived > 0)) {
        setScore("horde_active", 1);
        console.log("NIGHT IS ONGOING");
        startHordeNight();
    }

    // End Horde Night at 23,000
    if (isHordeNightActive && ((currentTime >= 23000 && lastCheckedTime < 23000) || !(daysSurvived % daysUntilHorde === 0 && daysSurvived > 0))) {
        setScore("horde_active", 0);
        console.log("NIGHT IS OVER");
        endHordeNight();
    }

    lastCheckedTime = currentTime;
}, 20);



export function skipDay() {
    world.setTimeOfDay(23999);
    lastCheckedTime = 23999;
    setScore("horde_active", 0);
    toggleHordeEffects(false);
    clearAllEffects();
}