import settings from "../settings/settings";
import { addAction } from "../util/broadcast";
import { makeObjectDraggable } from "Draggable";

const URL = "https://api.soopy.dev/skyblock/chevents/get";

const chEvents = ["BETTER_TOGETHER", "GONE_WITH_THE_WIND", "DOUBLE_POWDER"];
const dmEvents = ["GOBLIN_RAID", "RAFFLE", "MITHRIL_GOURMAND", ...chEvents];

let lastChecked = 0;
const lastNotifiedEvents = {};
const storedEvents = {
    DWARVEN_MINES: [],
    CRYSTAL_HOLLOWS: []
};

const text = new Text("", 10, 10);
const gui = new Gui();
let mouseDown = false;

function formatTime(msLeft) {
    let seconds = Math.max(0, Math.round(msLeft / 1000));
    let minutes = Math.floor(seconds / 60);
    let remain = seconds % 60;
    return `§d${minutes}m ${remain}s`;
}

function prettifyName(name) {
    return name.replace(/_/g, " ")
               .toLowerCase()
               .replace(/\b\w/g, c => c.toUpperCase());
}

function fetchAndNotifyEvents() {
    try {
        if (!settings().eventNotification) return;

        const chosenDwarvenEvent = dmEvents[settings().dmEvent];
        const chosenHollowsEvent = chEvents[settings().chEvent];

        const response = FileLib.getUrlContent(URL);
        let json = JSON.parse(response);
        let data = json.data;
        let currTime = data.curr_time;

        function notifyAndStore(regionKey, regionName, targetEvent) {
            let events = data.running_events[regionKey];
            storedEvents[regionKey] = [];

            if (!events) return;

            for (let event of events) {
                let isSelected = event.event.includes(targetEvent);

                storedEvents[regionKey].push({
                    name: event.event,
                    originalEndTime: event.ends_at,
                    remainingTime: event.ends_at - currTime,
                    isSelected: isSelected,
                    regionName: regionName
                });

                if (isSelected && lastNotifiedEvents[regionKey] !== event.event) {
                    let msLeft = event.ends_at - currTime;
                    let timeStr = formatTime(msLeft);
                    World.playSound("random.orb", 100, 0.7936508059501648);
                    ChatLib.chat(`§d[BlingBling Addons] §b${prettifyName(targetEvent)} §fin §e${regionName} §fis active! Ends in ${timeStr}`);
                    lastNotifiedEvents[regionKey] = event.event;
                }

                if (!isSelected && lastNotifiedEvents[regionKey] === event.event) {
                    delete lastNotifiedEvents[regionKey];
                }
            }
        }

        notifyAndStore("DWARVEN_MINES", "Dwarven Mines", chosenDwarvenEvent);
        notifyAndStore("CRYSTAL_HOLLOWS", "Crystal Hollows", chosenHollowsEvent);

    } catch (e) {
        ChatLib.chat("§d[BlingBling Addons] §c[Error] Could not fetch event data: " + e.message);
    }
}

register("renderOverlay", () => {
    if (settings().eventGui) {
        let lines = ["§d[BlingBling Addons] §7Active Events:"];

        function appendEvents(regionKey, regionName) {
            const events = storedEvents[regionKey];
            if (!events || events.length === 0) {
                lines.push(`§e${regionName}: §7No events running.`);
                return;
            }

            let addedAny = false;

            for (let event of events) {
                if (event.remainingTime <= 0) continue;

                let timeStr = formatTime(event.remainingTime);
                const nameStr = prettifyName(event.name);
                const color = event.isSelected ? "§4" : "§b";
                lines.push(`§e${regionName} §7- ${color}${nameStr} §d(${timeStr})§7`);

                addedAny = true;
            }

            if (!addedAny) {
                lines.push(`§e${regionName}: §7No active events.`);
            }
        }

        appendEvents("DWARVEN_MINES", "Dwarven Mines");
        appendEvents("CRYSTAL_HOLLOWS", "Crystal Hollows");

        text.setString(lines.join("\n"));
        text.draw();
    }
});

register("step", () => {
    const currentTime = Date.now();
    if (currentTime - lastChecked > 60000) {
        fetchAndNotifyEvents();
        lastChecked = currentTime;
    }
}).setDelay(60);

register("step", () => {
    for (let regionKey in storedEvents) {
        for (let event of storedEvents[regionKey]) {
            if (event.remainingTime > 0) {
                event.remainingTime -= 1000;
            }
        }
    }
}).setFps(1);

register("command", () => {
    ChatLib.chat("§d[BlingBling Addons] §7Current Events:");

    function appendEvents(regionKey, regionName) {
        const events = storedEvents[regionKey];
        if (!events || events.length === 0) {
            ChatLib.chat(`§e${regionName}: §7No events running.`);
            return;
        }

        let addedAny = false;

        for (let event of events) {
            if (event.remainingTime <= 0) continue;

            const nameStr = prettifyName(event.name);
            const color = event.isSelected ? "§4" : "§b";
            const timeStr = formatTime(event.remainingTime);
            ChatLib.chat(`§e${regionName} §7- ${color}${nameStr} §d(${timeStr})§7`);
            addedAny = true;
        }

        if (!addedAny) {
            ChatLib.chat(`§e${regionName}: §7No active events.`);
        }
    }

    appendEvents("DWARVEN_MINES", "Dwarven Mines");
    appendEvents("CRYSTAL_HOLLOWS", "Crystal Hollows");
}).setName("miningevents");

makeObjectDraggable("Mining Events", text, () => gui.isOpen() && mouseDown);

register("guiMouseClick", (mx, my, b, activeGui) => {
    if (activeGui.equals(gui)) mouseDown = true;
});

register("guiMouseRelease", () => {
    mouseDown = false;
});

addAction('moveEvents', () => gui.open());

fetchAndNotifyEvents();
