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

const MESSAGE_WINDOW = 1.5 * 1000; // 1.5 seconds window
const MUTE_DURATION = 30 * 1000;   // 30 seconds mute
const SPAM_LIMIT = 3;

const playerMessageTimes = new Map();
const mutedPlayers = new Map();
const unmuteNotified = new Set();  // Track who got unmute notification

const rankFormats = [
    {
        tag: "gwim:Admin",
        prefix: "",
        chatColor: "§c",
        nameColor: "§c"
    },
    {
        tag: "gwim:Owner",
        prefix: "",
        chatColor: "§4",
        nameColor: "§4"
    },
    {
        tag: "gwim:Warrior",
        prefix: "§8[§l§4Warrior§r§8]§r",
        chatColor: "§c",
        nameColor: "§c"
    },
    {
        tag: "gwim:Miner",
        prefix: "§8[§l§2Miner§r§8]§r",
        chatColor: "§a",
        nameColor: "§2"
    },
    {
        tag: "gwim:Healer",
        prefix: "§8[§l§5Healer§r§8]§r",
        chatColor: "§d",
        nameColor: "§d"
    },
    {
        tag: "gwim:VIP",
        prefix: "",
        chatColor: "§g",
        nameColor: "§6"
    },
    {
        tag: "gwim:VIPPlus",
        prefix: "",
        chatColor: "§g",
        nameColor: "§6"
    },
    {
        tag: "gwim:Elite",
        prefix: "",
        chatColor: "§3",
        nameColor: "§b"
    },
    {
        tag: "gwim:ElitePlus",
        prefix: "",
        chatColor: "§3",
        nameColor: "§b"
    },
    {
        tag: "gwim:God",
        prefix: "",
        chatColor: "§d",
        nameColor: "§5"
    }
];

// Update name tags every second
system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const tags = player.getTags();
        const playerName = player.name;
        let displayPrefix = "";
        let nameColor = "§7";

        for (const rank of rankFormats) {
            if (tags.includes(rank.tag)) {
                displayPrefix = rank.prefix;
                nameColor = rank.nameColor;
                break;
            }
        }

        player.nameTag = `${displayPrefix} ${nameColor}${playerName}`;
    }
}, 20);

// Interval to check for unmute and notify immediately
system.runInterval(() => {
    const now = Date.now();

    for (const [playerName, unmuteTime] of mutedPlayers.entries()) {
        if (now >= unmuteTime) {
            const player = world.getPlayers().find(p => p.name === playerName);
            if (player && !unmuteNotified.has(playerName)) {
                player.sendMessage("§aYou have been unmuted. Please avoid spamming.");
                player.playSound("random.orb");
                unmuteNotified.add(playerName);
            }
            mutedPlayers.delete(playerName);
            playerMessageTimes.delete(playerName);
        }
    }

    // Clear notified players who are no longer muted
    for (const notifiedName of unmuteNotified) {
        if (!mutedPlayers.has(notifiedName)) {
            unmuteNotified.delete(notifiedName);
        }
    }
}, 20); // check every second

// Chat handling with mute on spam
world.beforeEvents.chatSend.subscribe((data) => {
    const player = data.sender;
    const playerName = player.name;
    const now = Date.now();

    // Check if muted
    if (mutedPlayers.has(playerName)) {
        const unmuteTime = mutedPlayers.get(playerName);
        if (now < unmuteTime) {
            const remaining = Math.ceil((unmuteTime - now) / 1000);
            data.cancel = true;
            player.sendMessage(`§cYou are muted. Remaining time: §e${remaining}s`);
            system.run(() => player.playSound("note.bass"));
            return;
        }
    }

    // Record this message time
    if (!playerMessageTimes.has(playerName)) {
        playerMessageTimes.set(playerName, []);
    }
    const times = playerMessageTimes.get(playerName);

    // Remove old messages outside the 1.5s window
    while (times.length > 0 && times[0] < now - MESSAGE_WINDOW) {
        times.shift();
    }

    times.push(now);

    // If 3 or more messages within 1.5 seconds, mute player
    if (times.length >= SPAM_LIMIT) {
        mutedPlayers.set(playerName, now + MUTE_DURATION);
        unmuteNotified.delete(playerName); // reset notification for this mute cycle
        data.cancel = true;
        player.sendMessage(`§cYou have been muted for §e30 seconds §cfor spamming.`);
        system.run(() => player.playSound("random.break"));
        return;
    }

    // Rank formatting and sending chat message
    const tags = player.getTags();
    let prefix = "";
    let chatColor = "§7";
    let nameColor = "§7";

    for (const rank of rankFormats) {
        if (tags.includes(rank.tag)) {
            prefix = rank.prefix;
            chatColor = rank.chatColor;
            nameColor = rank.nameColor;
            break;
        }
    }

    const formatted = `${prefix} ${nameColor}${playerName} > ${chatColor}${data.message}§r`;
    world.sendMessage({ rawtext: [{ text: formatted }] });

    data.cancel = true;
});