-- TOG Tools — Name Prefix tab (UI)
-- Settings panel for the NamePrefix module, rendered inside the main window.

local _, addon = ...
local AceGUI = LibStub("AceGUI-3.0")

local BRAND = "|cffFF8000"

-- ---------------------------------------------------------------------------
-- Tab module table — merges UI fields into the engine table registered
-- by Modules/NamePrefix/NamePrefix.lua (which loads before this file).
-- ---------------------------------------------------------------------------
local Tab = addon.modules["nameprefix"]
Tab.tabKey      = "nameprefix"
Tab.configKey   = "namePrefix"   -- db.global section holding this module's settings + enabled flag
Tab.label       = "Name Prefix"
Tab.WINDOW_SIZE = { width = 560, height = 480, locked = true }
Tab.help = {
    title = "Name Prefix",
    lines = {
        "Automatically prepends a nickname to your chat messages so guildmates know who you are even on alts.",
        "Set a nickname and a format string (e.g. |cffffd700(Name):|r, |cffffd700[Name]|r, |cffffd700Name —|r). Live preview updates as you type.",
        "Tick the channels to prefix on: Say, Guild, Officer, Party, Raid, Instance, or a specific custom channel by name.",
        "Messages starting with |cffffd700!|r are skipped (configurable) so addon commands like |cffffd700!keys|r aren't prefixed.",
        "Account-wide: configure once, applies to every alt. Characters whose own name already matches the nickname auto-skip the prefix (configurable).",
    },
}

-- ---------------------------------------------------------------------------
-- Helpers
-- ---------------------------------------------------------------------------
local function cfg()
    return addon.DB.global.namePrefix
end

-- Build the live preview string shown below the format field.
local function BuildPreview()
    local c = cfg()
    local nick = (c.nickname ~= "") and c.nickname or "Nickname"
    local fmt  = (c.format   ~= "") and c.format   or "(%s): "
    local ok, result = pcall(string.format, fmt, nick)
    if ok then
        return BRAND .. "Preview:|r " .. result .. "Hello guild!"
    else
        return "|cffff4444Invalid format string|r"
    end
end

-- Channels that can be toggled on/off.
local CHAT_CHANNELS = {
    { key = "say",      label = "Say  (/s)",                   order = 1 },
    { key = "guild",    label = "Guild  (/g)",                 order = 2 },
    { key = "officer",  label = "Officer  (/o)",               order = 3 },
    { key = "party",    label = "Party  (/p)",                 order = 4 },
    { key = "raid",     label = "Raid  (/ra)",                 order = 5 },
    { key = "instance", label = "Instance / BG  (/i)",        order = 6 },
}

-- ---------------------------------------------------------------------------
-- Draw
-- ---------------------------------------------------------------------------
function Tab:Draw(container)
    local c = cfg()

    -- -----------------------------------------------------------------------
    -- Outer scroll container so the panel works at any window height
    -- -----------------------------------------------------------------------
    local scroll = AceGUI:Create("ScrollFrame")
    scroll:SetLayout("Flow")
    scroll:SetFullWidth(true)
    scroll:SetFullHeight(true)
    container:AddChild(scroll)

    -- -----------------------------------------------------------------------
    -- Section: Enable toggle + status line
    -- -----------------------------------------------------------------------
    local enableCheck = AceGUI:Create("CheckBox")
    enableCheck:SetLabel(BRAND .. "Enable Name Prefix|r")
    enableCheck:SetValue(c.enabled)
    enableCheck:SetFullWidth(true)
    enableCheck:SetCallback("OnValueChanged", function(_, _, val)
        c.enabled = val
        self:Refresh(container)
        -- Same flag the Settings > Modules toggle writes to; rebuild the
        -- main window so the tab disappears (or reappears) immediately.
        if addon.MainWindow and addon.MainWindow.Rebuild then
            addon.MainWindow:Rebuild()
        end
    end)
    scroll:AddChild(enableCheck)

    -- Spacer
    local sp1 = AceGUI:Create("Label")
    sp1:SetText(" ")
    sp1:SetFullWidth(true)
    scroll:AddChild(sp1)

    -- -----------------------------------------------------------------------
    -- Section: Nickname
    -- -----------------------------------------------------------------------
    local nickHeader = AceGUI:Create("Label")
    nickHeader:SetText(BRAND .. "Nickname|r")
    nickHeader:SetFullWidth(true)
    scroll:AddChild(nickHeader)

    local nickEdit = AceGUI:Create("EditBox")
    nickEdit:SetLabel("Nickname to insert into chat")
    nickEdit:SetText(c.nickname or "")
    nickEdit:SetRelativeWidth(0.6)
    nickEdit:DisableButton(true)
    nickEdit:SetCallback("OnTextChanged", function(_, _, val)
        c.nickname = strtrim(val)
        -- Refresh preview label without redrawing the whole tab
        if self._previewLabel then
            self._previewLabel:SetText(BuildPreview())
        end
    end)
    scroll:AddChild(nickEdit)

    -- -----------------------------------------------------------------------
    -- Section: Format string
    -- -----------------------------------------------------------------------
    local fmtHeader = AceGUI:Create("Label")
    fmtHeader:SetText(" ")
    fmtHeader:SetFullWidth(true)
    scroll:AddChild(fmtHeader)

    local fmtLabel = AceGUI:Create("Label")
    fmtLabel:SetText(BRAND .. "Prefix Format|r")
    fmtLabel:SetFullWidth(true)
    scroll:AddChild(fmtLabel)

    local fmtEdit = AceGUI:Create("EditBox")
    fmtEdit:SetLabel("Format string  (%s = your nickname)")
    fmtEdit:SetText(c.format or "(%s): ")
    fmtEdit:SetRelativeWidth(0.6)
    fmtEdit:DisableButton(true)
    fmtEdit:SetCallback("OnTextChanged", function(_, _, val)
        c.format = val
        if self._previewLabel then
            self._previewLabel:SetText(BuildPreview())
        end
    end)
    scroll:AddChild(fmtEdit)

    -- Format hint examples
    local fmtHint = AceGUI:Create("Label")
    fmtHint:SetText("|cffaaaaaa  Examples:  (%s):    [%s]    %s ►|r")
    fmtHint:SetFullWidth(true)
    scroll:AddChild(fmtHint)

    -- Live preview
    local previewLabel = AceGUI:Create("Label")
    previewLabel:SetText(BuildPreview())
    previewLabel:SetFullWidth(true)
    scroll:AddChild(previewLabel)
    self._previewLabel = previewLabel

    -- -----------------------------------------------------------------------
    -- Section: Channel toggles
    -- -----------------------------------------------------------------------
    local sp2 = AceGUI:Create("Label")
    sp2:SetText(" ")
    sp2:SetFullWidth(true)
    scroll:AddChild(sp2)

    local chanHeader = AceGUI:Create("Label")
    chanHeader:SetText(BRAND .. "Active Channels|r")
    chanHeader:SetFullWidth(true)
    scroll:AddChild(chanHeader)

    for _, ch in ipairs(CHAT_CHANNELS) do
        local cb = AceGUI:Create("CheckBox")
        cb:SetLabel(ch.label)
        cb:SetValue(c[ch.key])
        cb:SetRelativeWidth(0.5)
        cb:SetCallback("OnValueChanged", function(_, _, val)
            c[ch.key] = val
        end)
        scroll:AddChild(cb)
    end

    -- Custom channel name
    local sp3 = AceGUI:Create("Label")
    sp3:SetText(" ")
    sp3:SetFullWidth(true)
    scroll:AddChild(sp3)

    local chanEdit = AceGUI:Create("EditBox")
    chanEdit:SetLabel("Custom channel name  (leave blank to disable)")
    chanEdit:SetText(c.channel or "")
    chanEdit:SetRelativeWidth(0.6)
    chanEdit:DisableButton(true)
    chanEdit:SetCallback("OnTextChanged", function(_, _, val)
        c.channel = strtrim(val)
    end)
    scroll:AddChild(chanEdit)

    local chanHint = AceGUI:Create("Label")
    chanHint:SetText("|cffaaaaaa  Matches the channel name, not its number (e.g. \"General\", \"Trade\").|r")
    chanHint:SetFullWidth(true)
    scroll:AddChild(chanHint)

    -- -----------------------------------------------------------------------
    -- Section: Behaviour options
    -- -----------------------------------------------------------------------
    local sp4 = AceGUI:Create("Label")
    sp4:SetText(" ")
    sp4:SetFullWidth(true)
    scroll:AddChild(sp4)

    local optHeader = AceGUI:Create("Label")
    optHeader:SetText(BRAND .. "Options|r")
    optHeader:SetFullWidth(true)
    scroll:AddChild(optHeader)

    local skipExclCheck = AceGUI:Create("CheckBox")
    skipExclCheck:SetLabel("Skip messages starting with  !")
    skipExclCheck:SetDescription("Prevents the prefix being added to addon commands like !keys or !roll.")
    skipExclCheck:SetValue(c.skipExclamation)
    skipExclCheck:SetFullWidth(true)
    skipExclCheck:SetCallback("OnValueChanged", function(_, _, val)
        c.skipExclamation = val
    end)
    scroll:AddChild(skipExclCheck)

    local hideCharCheck = AceGUI:Create("CheckBox")
    hideCharCheck:SetLabel("Hide prefix if nickname matches character name")
    hideCharCheck:SetDescription("Suppresses the prefix on characters where your nickname is the same as your character's name — avoiding '(Arthas): Arthas says...'.")
    hideCharCheck:SetValue(c.hideIfCharName)
    hideCharCheck:SetFullWidth(true)
    hideCharCheck:SetCallback("OnValueChanged", function(_, _, val)
        c.hideIfCharName = val
    end)
    scroll:AddChild(hideCharCheck)
end

function Tab:Refresh(container)
    -- Full redraw when enabled state changes (greys out nothing for now,
    -- but keeps the pattern consistent with other tabs that do react).
    container:ReleaseChildren()
    self:Draw(container)
end
