local window = nil
local selectedReward = nil
local consoleEvent = nil

function init()
    connect(g_game, {
        onGameStart = onGameStart,
        onGameEnd = destroy
    })

    ProtocolGame.registerExtendedJSONOpcode(216, parseOpcode)
end

function terminate()
    disconnect(g_game, {
        onGameEnd = destroy
    })
    ProtocolGame.unregisterExtendedJSONOpcode(216, parseOpcode)
    destroy()
end

function onGameStart()
    if window then
        window:destroy()
        window = nil
    end
end

function destroy()
    if window then
        window:destroy()
        window = nil
    end
    selectedReward = nil
end

function parseOpcode(protocol, opcode, data)
    if data['action'] == 'data' then
        showShop(data)
    elseif data['action'] == 'message' then
        setInfoText(data['message'], data['color'])
    end
end

function sendOpcode(data)
    local protocolGame = g_game.getProtocolGame()
    if protocolGame then
        protocolGame:sendExtendedJSONOpcode(216, data)
    end
end

function onItemSelect(list, focusedChild, unfocusedChild, reason)
    if focusedChild then
        selectedReward = focusedChild.rewardId
        if selectedReward then
            window.buyButton:setEnabled(true)
        end
    end
end

function showShop(data)
    if not window then
        window = g_ui.displayUI('taskshop')
    end

    window:setVisible(true)
    window:raise()
    window:focus()

    -- Update points display
    local points = data['points'] or 0
    window.pointsLabel:setText('Task Points: ' .. points)

    -- Clear existing items
    local itemsPanel = window.itemsPanel
    itemsPanel.onChildFocusChange = nil
    itemsPanel:destroyChildren()
    selectedReward = nil
    window.buyButton:setEnabled(false)

    -- Populate reward items
    for _, reward in ipairs(data['rewards']) do
        local itemBox = g_ui.createWidget('ShopRewardItem', itemsPanel)
        itemBox.rewardId = reward.id

        -- Server sends client ID directly (converted via ItemType:getClientId())
        local itemWidget = itemBox:getChildById('itemWidget')
        itemWidget:setItemId(reward.itemId)
        itemWidget:setItemCount(reward.itemCount or 1)

        -- Set name and cost
        itemBox:getChildById('nameLabel'):setText(reward.name)
        itemBox:getChildById('costLabel'):setText(reward.cost .. ' pts')
    end

    -- Set callback and select first item
    itemsPanel.onChildFocusChange = onItemSelect
    if itemsPanel:getFirstChild() then
        local firstChild = itemsPanel:getFirstChild()
        itemsPanel:focusChild(firstChild)
        selectedReward = firstChild.rewardId
        window.buyButton:setEnabled(true)
    end
end

function buy()
    if not selectedReward then
        setInfoText("Select a reward first.", "red")
        return
    end

    sendOpcode({
        action = 'buy',
        entry = selectedReward
    })
end

function hideWindow()
    if window and window:isVisible() then
        window:setVisible(false)
    end
end

function setInfoText(text, color)
    if not window then return end

    if not color then
        color = 'white'
    end

    window.infoLabel:setText(text)
    window.infoLabel:setColor(color)

    if consoleEvent then
        removeEvent(consoleEvent)
        consoleEvent = nil
    end

    consoleEvent = scheduleEvent(function()
        if window then
            window.infoLabel:setText('')
        end
    end, 5000)
end
