local PT = AhUI
if not PT then return end

local L = PT.L
local WhatsNew = {}
PT.WhatsNewUI = WhatsNew

local ADDON_NAME = "AhUI"
local FONT = AhUI.FONT

local function GetAddonVersion()
    return C_AddOns.GetAddOnMetadata(ADDON_NAME, "Version") or "0.0.0"
end

local function ParseVersion(v)
    local major, minor, patch = string.match(v, "(%d+)%.(%d+)%.?(%d*)")
    return tonumber(major) or 0,
           tonumber(minor) or 0,
           tonumber(patch) or 0
end

local function IsVersionGreater(a, b)
    local a1,a2,a3 = ParseVersion(a)
    local b1,b2,b3 = ParseVersion(b)

    if a1 ~= b1 then return a1 > b1 end
    if a2 ~= b2 then return a2 > b2 end
    return a3 > b3
end

local CATEGORY_STYLES = {
    NEW      = "|cff3cff00[NEW]|r ",
    FIX      = "|cffff3c3c[FIX]|r ",
    IMPROVED = "|cff00bfff[IMPROVED]|r ",
    CHANGED  = "|cffffa500[CHANGED]|r ",
}

local CHANGELOG = {

    ["1.2.3"] = {
        {
            type = "NEW",
            ru = "Добавлено сокрытие аддона в инстансах (чекбокс в настройках).",
            en = "Added automatic addon hiding in instances (toggle available in Settings)."
        }
    },

    ["1.2.2"] = {

        {
            type = "IMPROVED",
            ru = "Шрифт элементов инфопанели теперь масштабируется вместе с высотой панели.",
            en = "InfoPanel element fonts now scale dynamically with panel height."
        },

        {
            type = "CHANGED",
            ru = "Изменён подход к уведомлениям о капе концентрации — теперь можно включать уведомления отдельно для каждой профессии.",
            en = "Concentration cap notifications reworked — notifications can now be enabled per profession."
        },

        {
            type = "FIX",
            ru = "Исправлен офлайн-реген концентрации в обзоре персонажа — реген больше не происходит, если профессия отсутствует.",
            en = "Fixed offline concentration regeneration in Character Overview — no regeneration occurs if the profession is missing."
        },

        {
            type = "NEW",
            ru = "Добавлен выбор отображаемого дополнения в окнах концентрации и очков знаний.",
            en = "Added expansion selection for Concentration and Knowledge Points windows."
        },

        {
            type = "NEW",
            ru = "Добавлен выбор типа попапа (диалогового окна) для кнопки подтверждения.",
            en = "Added popup type selection for confirmation buttons."
        },

        {
            type = "NEW",
            ru = "Добавлен модуль руководств профессий (/pg) — подробности по команде. Модуль в разработке.",
            en = "Added Profession Guides module (/pg) — see command for details. Still in development."
        },
    },
}

local function BuildFullChangelog()

    local versions = {}

    for v in pairs(CHANGELOG) do
        table.insert(versions, v)
    end

    table.sort(versions, function(a,b)
        return IsVersionGreater(a,b)
    end)

    local result = ""

    for _, version in ipairs(versions) do

        result = result ..
            "|cffFFD100VERSION " .. version .. "|r\n\n"

        for _, entry in ipairs(CHANGELOG[version]) do

            local tag = CATEGORY_STYLES[entry.type] or ""

            result = result ..
                tag .. "|cffFFFFFF" .. entry.ru .. "|r\n" ..
                tag .. "|cffaaaaaa" .. entry.en .. "|r\n\n"
        end

        result = result .. "\n"
    end

    return result
end

function WhatsNew:Create()
    if self.frame then return self.frame end

    AhUI_DB = AhUI_DB or {}

    local f = CreateFrame("Frame", "AhUIWhatsNewFrame", UIParent, "BackdropTemplate")
    f:SetSize(520, 460)
    f:SetPoint("CENTER")
    f:SetFrameStrata("DIALOG")

    f:SetBackdrop({
        bgFile   = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Buttons\\WHITE8x8",
        edgeSize = 3,
    })

    f:SetBackdropColor(0,0,0,0.95)
    f:SetBackdropBorderColor(1,1,1,1)

    f:Hide()
    tinsert(UISpecialFrames, f:GetName())

    local logo = f:CreateTexture(nil, "ARTWORK")
    logo:SetSize(96,96)
    logo:SetPoint("TOP",0,-18)
    logo:SetTexture("Interface\\AddOns\\AhUI\\media\\logo.png")

    local title = f:CreateFontString(nil,"OVERLAY")
    title:SetFont(FONT,16,"OUTLINE")
    title:SetPoint("TOP",logo,"BOTTOM",0,-10)
    title:SetText("What's New?")

    local scrollFrame = CreateFrame("ScrollFrame",nil,f,"UIPanelScrollFrameTemplate")
    scrollFrame:SetPoint("TOPLEFT",40,-140)
    scrollFrame:SetPoint("BOTTOMRIGHT",-40,70)

    local content = CreateFrame("Frame",nil,scrollFrame)
    content:SetSize(420,1200)
    scrollFrame:SetScrollChild(content)

    local text = content:CreateFontString(nil,"OVERLAY")
    text:SetFont(FONT,14,"")
    text:SetPoint("TOPLEFT")
    text:SetWidth(400)
    text:SetJustifyH("LEFT")
    text:SetJustifyV("TOP")
    text:SetWordWrap(true)

    text:SetText(BuildFullChangelog())

    local btn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    btn:SetSize(140,26)
    btn:SetPoint("BOTTOM",0,20)
    btn:SetText("Close")

    local fs = btn:GetFontString()
    if fs then fs:SetFont(FONT,13,"") end

    btn:SetScript("OnClick", function()
        AhUI_DB.lastShownVersion = GetAddonVersion()
        f:Hide()
    end)

    self.frame = f
    return f
end

function WhatsNew:Show()
    self:Create():Show()
end

local ev = CreateFrame("Frame")
ev:RegisterEvent("PLAYER_LOGIN")
ev:SetScript("OnEvent", function()

    AhUI_DB = AhUI_DB or {}

    local current = GetAddonVersion()
    local last    = AhUI_DB.lastShownVersion

    if last ~= current then
        C_Timer.After(0.8, function()
            WhatsNew:Show()
        end)
    end
end)

SLASH_AHUIWHATSNEW1 = "/ahuiwhatsnew"
SLASH_AHUIWHATSNEW2 = "/ahwn"

SlashCmdList["AHUIWHATSNEW"] = function()
    WhatsNew:Show()
end