local TELEPORTS = {
    Rotworm = {level = 8, pos = Position(32369, 32241, 7)},
    Minotaur = {level = 8, pos = Position(32369, 32241, 7)},
    Cyclops = {level = 20, pos = Position(32369, 32241, 7)},
        Yielothax = {level = 20, pos = Position(32369, 32241, 7)},
}

-- Mapa ID wyboru → nazwa potwora
local teleportChoices = {}

local function countdownAndTeleport(playerId, name, position, countdown)
    local player = Player(playerId)
    if not player then return end

    if countdown == 0 then
        player:teleportTo(position)
        player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
        player:say(name .. " awaits you!", TALKTYPE_MONSTER_SAY)
        return
    end

    player:say(tostring(countdown), TALKTYPE_MONSTER_SAY)
    addEvent(countdownAndTeleport, 1000, playerId, name, position, countdown - 1)
end

local function openTeleportModal(player)
    local window = ModalWindow(35477, "Choose your destination", "Select a monster to hunt.")
    window:addButton(1, "Teleports")
    window:addButton(2, "Back")

    teleportChoices = {}  -- czyścimy mapę

    for name, _ in pairs(TELEPORTS) do
        local choiceId = window:addChoice(name, name)
        teleportChoices[choiceId] = name
    end

    window:setDefaultEnterButton(1)
    window:setDefaultEscapeButton(2)

    window:sendToPlayer(player)
end

function onModalWindow(player, modalId, buttonId, choiceId)
    if modalId ~= 35477 then return false end

    if buttonId == 2 then
        player:sendTextMessage(MESSAGE_INFO_DESCR, "Modal closed.")
        return true
    end

    local choiceName = teleportChoices[choiceId]
    if not choiceName then
        player:sendTextMessage(MESSAGE_STATUS_SMALL, "Invalid selection.")
        return true
    end

    local destination = TELEPORTS[choiceName]
    if not destination then
        player:sendTextMessage(MESSAGE_STATUS_SMALL, "Destination not found.")
        return true
    end

    if player:getLevel() < destination.level then
        player:sendCancelMessage("You need to be at least level " .. destination.level .. " to hunt " .. choiceName .. "s.")
        return true
    end

    player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "Preparing teleport to " .. choiceName .. "...")
    countdownAndTeleport(player:getId(), choiceName, destination.pos, 3)

    return true
end

function onStepIn(creature, item, position, fromPosition)
    local player = creature:getPlayer()
    if not player then return true end

    if item.actionid == 35477 then
        openTeleportModal(player)
    end
    return true
end
