-- RUQuestLog_QuestGiver.lua (TBCC 2.5.5)
-- Перевод текста у NPC (Quest Giver) через события, без влияния на квест-лог.

local function isEnabled()
    return RUQuestLogDB and RUQuestLogDB.enabled ~= false
end

local function chat(msg)
    if DEFAULT_CHAT_FRAME and DEFAULT_CHAT_FRAME.AddMessage then
        DEFAULT_CHAT_FRAME:AddMessage("|cff66ccffRUQL-QG|r " .. tostring(msg))
    end
end

local function later(fn)
    if C_Timer and C_Timer.After then
        C_Timer.After(0, fn)
    else
        fn()
    end
end

-- Пытаемся достать questID максимально “по-современному” и максимально “по-классике”
local function getQuestGiverQuestID()
    local id

    if GetQuestID then
        id = GetQuestID()
        if type(id) == "number" and id > 0 then return id end
    end
    if QuestGetQuestID then
        id = QuestGetQuestID()
        if type(id) == "number" and id > 0 then return id end
    end

    id = (QuestInfoFrame and QuestInfoFrame.questID) or (QuestFrame and QuestFrame.questID)
    if type(id) == "number" and id > 0 then return id end

    return nil
end

local function getRowByQuestID(qid)
    local db = RUQuestLogDB and RUQuestLogDB.quest
    return (db and qid and db[qid]) or nil
end

local function FS_Desc()
    return QuestDescriptionText or QuestInfoDescriptionText or _G.QuestInfoDescriptionText
end
local function FS_Obj()
    return QuestObjectivesText or QuestInfoObjectivesText or _G.QuestInfoObjectivesText
end
local function FS_Prog()
    return QuestProgressText or QuestInfoProgressText or _G.QuestInfoProgressText
end
local function FS_Rew()
    return QuestRewardText or QuestInfoRewardText or _G.QuestInfoRewardText
end

-- --- Лейблы "Quest Objectives" / "Rewards" ---

local function normalize(s)
    if type(s) ~= "string" then return nil end
    return s:gsub("\r\n", "\n"):gsub("\r", "\n")
end

local function walkFontStrings(frame, out)
    if not frame then return end

    if frame.GetRegions then
        local regions = { frame:GetRegions() }
        for _, r in ipairs(regions) do
            if r and r.GetObjectType and r:GetObjectType() == "FontString" then
                out[#out + 1] = r
            end
        end
    end

    if frame.GetNumChildren then
        for i = 1, frame:GetNumChildren() do
            walkFontStrings(select(i, frame:GetChildren()), out)
        end
    end
end

local function translateQuestGiverLabels()
    local ok = false

    local function setTitle(fs, txt)
        if fs and fs.SetText then
            -- если твоя глобалка принимает addonName:
            fs:SetText(txt)
            RUQL_setRuTitleFont(fs)
            return true
        end
        return false
    end

    -- 1) Известные хедеры (тут тоже ставим шрифт)
    ok = setTitle(_G.QuestInfoObjectivesHeader, "Цели") or ok
    ok = setTitle(_G.QuestInfoObjectivesTextHeader, "Цели") or ok
    ok = setTitle(_G.QuestObjectivesTitleText, "Цели") or ok

    if _G.QuestInfoRewardsFrame then
        ok = setTitle(_G.QuestInfoRewardsFrame.Header, "Награды") or ok
        ok = setTitle(_G.QuestInfoRewardsFrame.HeaderText, "Награды") or ok
    end
    ok = setTitle(_G.QuestRewardsTitleText, "Награды") or ok

    -- 2) Fallback: сканируем FontString'и и меняем точечно по тексту
    local root = QuestFrame or QuestInfoFrame
    if root then
        local list = {}
        walkFontStrings(root, list)

        for _, fs in ipairs(list) do
            local t = normalize(fs:GetText())
            if t and t ~= "" then
                local tl = t:lower()

                if tl == "quest objectives" or tl == "objectives" then
                    ok = setTitle(fs, "Цели") or ok
                elseif tl == "rewards" then
                    ok = setTitle(fs, "Награды") or ok
                elseif tl == "required items:" or tl == "required items" then
                    ok = setTitle(fs, "Требуемые предметы:") or ok
                end

            end
        end
    end

    return ok
end

local function translateQuestGiverRewardsLines()
    local root = QuestFrame or QuestInfoFrame
    if not root then return end

    local list = {}
    walkFontStrings(root, list)

    for _, fs in ipairs(list) do
        local t = normalize(fs:GetText())
        if t and t ~= "" then
            local tl = t:lower()

            -- "Rewards" уже переводим отдельно, но пусть будет дубль без вреда
            if tl == "rewards" then
                fs:SetText("Награды")

            elseif tl:find("you will receive", 1, true) then
                -- важно: в UI бывает "You will receive:" с двоеточием/пробелами
                fs:SetText((t:gsub("[Yy]ou will receive%s*:", "Вы получите:")))

            elseif tl:find("you will be able to choose one of these rewards", 1, true) then
                fs:SetText("Вы сможете выбрать одну из этих наград:")

            elseif tl:find("you will also receive", 1, true) then
                fs:SetText("Также вы получите:")

            elseif tl:find("bonus honor", 1, true) then
                fs:SetText((t:gsub("[Bb]onus [Hh]onor", "Дополнительная честь")))
            end
        end
    end
end

local function applyQuestGiver(mode)
    if not isEnabled() then return end

    local qid = getQuestGiverQuestID()
    local row = getRowByQuestID(qid)

    -- В зависимости от состояния окна
    if mode == "detail" then
        local dfs = FS_Desc()
        if dfs and dfs.SetText and row.details and row.details ~= "" then
            dfs:SetText(RUQL_post(row.details))
        end

        local ofs = FS_Obj()
        if ofs and ofs.SetText and row.objectives and row.objectives ~= "" then
            ofs:SetText(RUQL_post(row.objectives))
        end

    elseif mode == "progress" then
        local pfs = FS_Prog()
        if pfs and pfs.SetText and row.progress and row.progress ~= "" then
            pfs:SetText(RUQL_post(row.progress))
        end

    elseif mode == "complete" then
        local rfs = FS_Rew()
        if rfs and rfs.SetText and row.completion and row.completion ~= "" then
            rfs:SetText(RUQL_post(row.completion))
        end
    end

    -- Лейблы (Quest Objectives / Rewards)
    translateQuestGiverLabels()
    translateQuestGiverRewardsLines()

    -- Лейбл (Header)
    local function applyTitleFallback()
        if not row.title or row.title == "" then return end

        local apiTitle
        if GetTitleText then
            apiTitle = normalize(GetTitleText())
        end
        if not apiTitle or apiTitle == "" then return end

        local root = QuestFrame or QuestInfoFrame
        if not root then return end

        local list = {}
        walkFontStrings(root, list)

        for _, fs in ipairs(list) do
            local t = normalize(fs:GetText())
            if t and t ~= "" and t == apiTitle then
                fs:SetText(RUQL_post(row.title))
                RUQL_setRuTitleFont(fs)
                return
            end
        end
    end
    applyTitleFallback()
end

local f = CreateFrame("Frame")
f:RegisterEvent("QUEST_DETAIL")
f:RegisterEvent("QUEST_PROGRESS")
f:RegisterEvent("QUEST_COMPLETE")
f:RegisterEvent("QUEST_GREETING")

f:SetScript("OnEvent", function(_, event)
    if event == "QUEST_DETAIL" then
        later(function() applyQuestGiver("detail") end)
    elseif event == "QUEST_PROGRESS" then
        later(function() applyQuestGiver("progress") end)
    elseif event == "QUEST_COMPLETE" then
        later(function() applyQuestGiver("complete") end)
    elseif event == "QUEST_GREETING" then
        later(function() applyQuestGiver("detail") end)
    end
end)

chat("QuestGiver module loaded")
