if not is_client then
    return
end

function init(node)
    local value = node:get_property_int("value") or 1
    local opt = node:get_property_string("option" .. value) or ""
    node:query():text():matches()(nil, nil):set_text(opt)
end

function open_dropdown(node)
    node:focus()

    local value = node:get_property_int("value") or 1
    local options = node:get_property_int("options") or 0

    local nx, ny, nw, nh = node:render_position()

    local display = ui.from_str([[
dropdown_catcher {
    dropdown_list(
        x=]] .. nx .. [[,
        y=]] .. ny + nh .. [[,
        width=]] .. nw .. [[,
        rows=]] .. options .. [[
    ) {
        scroll_panel {
            scroll_bar {
                scroll_thumb
            }
            content(rows=]] .. options .. [[) {

            }
        }
    }
}
    ]])

    local list = display:query()
        :name("dropdown_list")
        :child():name("scroll_panel")
        :child():name("content")
        :matches()(nil, nil)
    list:set_property_table("$dropdown", {
        box = node,
    })
    for i = 1, options do
        local opt = node:get_property_string("option" .. i) or ""
        list:add_child(ui.from_str([[
            entry(id = ]] .. tostring(i) .. [[, selected=]] .. tostring(i == value) .. [[) {
                content {
                    "]] .. opt .. [["
                }
            }
        ]]))
    end

    ui.add_node(display)
end

function close_dropdown()
    local dc = ui.query():name("dropdown_catcher"):matches()(nil, nil)
    if dc == nil then
        return
    end

    local list = dc:query()
        :name("dropdown_list")
        :child():name("scroll_panel")
        :child():name("content")
        :matches()(nil, nil)
    local box = list:get_property_table("$dropdown").box
    box:set_property_int("$value_hover", 0)

    ui.remove_node(dc)
end

function select_entry(node)
    local box = node.parent:get_property_table("$dropdown").box

    box:set_property_int("value", node:get_property_int("id") or 1)
    init(box)
    close_dropdown()
end

function hover_entry(node)
    local box = node.parent:get_property_table("$dropdown").box

    box:set_property_int("$value_hover", node:get_property_int("id") or 1)
end