local RUI = LibStub("RUI-1.0")
if not RUI then return end

-- RUI.Widget.TextInput(parent, label, x, y, width, get, set[, maxLetters]) → EditBox, Refresh(), label
-- Free-text input. Distinct from RUI.Widget.Input, which parses its contents as a
-- number and silently discards anything else -- use this one for names, messages,
-- and any other arbitrary string.
-- Commits on EnterPressed and on focus loss, so a click away is not silently lost.
-- Reverts to get() on EscapePressed.
-- Total height consumed: LABEL_H(14) + INPUT_H(20) + CONTROL_GAP(4) = 38px.
function RUI.Widget.TextInput(parent, label, x, y, width, get, set, maxLetters)
    local lbl = RUI.Draw.MakeLabel(parent)
    lbl:SetTextColor(RUI.C.TEXT.r, RUI.C.TEXT.g, RUI.C.TEXT.b)
    lbl:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
    lbl:SetWidth(width)
    lbl:SetJustifyH("LEFT")
    lbl:SetText(label)

    local eb = RUI.Draw.MakeInputBox(parent, width)
    eb:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y - RUI.LABEL_H)
    eb:SetMaxLetters(maxLetters or 64)

    local function Commit(self)
        set(self:GetText() or "")
        self:ClearFocus()
    end

    eb:SetScript("OnEnterPressed", Commit)
    -- Replaces MakeInputBox's handler, so clear the select-all highlight here too.
    eb:SetScript("OnEditFocusLost", function(self)
        self:HighlightText(0, 0)
        set(self:GetText() or "")
    end)
    eb:SetScript("OnEscapePressed", function(self)
        self:SetText(get() or "")
        self:ClearFocus()
    end)

    local function Refresh()
        eb:SetText(get() or "")
        eb:SetCursorPosition(0)
    end
    Refresh()
    return eb, Refresh, lbl
end
