-- EnglishLinks_Config.lua
-- Author: NightsPrower

EnglishLinksDB = EnglishLinksDB or {}

local defaults = {
    chatEnabled  = true,
    reverseMode  = false,
    lootEnabled  = true,
    hudScale     = 1.0,
}

local function initConfig()
    for k, v in pairs(defaults) do
        if EnglishLinksDB[k] == nil then
            EnglishLinksDB[k] = v
        end
    end
end

local EL_Config = {}
EnglishLinks_Config = EL_Config

function EL_Config.get(key) return EnglishLinksDB[key] end
function EL_Config.set(key, val) EnglishLinksDB[key] = val end

-- ================================================================
-- HUD
-- ================================================================
local panel = nil
local VERSION    = "1.1.0"
local ADDON_NAME = "English Links"
local AUTHOR     = "NightsPrower"
local CHECK_SIZE = 20

local function applyScale()
    if panel then
        panel:SetScale(EL_Config.get("hudScale") or 1.0)
    end
end

local function createCheckbox(parent, label, desc, key, xoff, yoff)
    local cb = CreateFrame("CheckButton", nil, parent, "UICheckButtonTemplate")
    cb:SetSize(CHECK_SIZE, CHECK_SIZE)
    cb:SetPoint("TOPLEFT", parent, "TOPLEFT", xoff, yoff)
    cb:SetChecked(EL_Config.get(key))

    local lbl = cb:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    lbl:SetPoint("LEFT", cb, "RIGHT", 6, 0)
    lbl:SetText(label)

    cb:SetScript("OnClick", function(self)
        EL_Config.set(key, self:GetChecked())
    end)

    cb:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
        GameTooltip:SetText(label, 1, 1, 1)
        if desc and desc ~= "" then
            GameTooltip:AddLine(desc, 0.8, 0.8, 0.8, true)
        end
        GameTooltip:Show()
    end)
    cb:SetScript("OnLeave", function() GameTooltip:Hide() end)

    return cb
end

local function createSlider(parent, xoff, yoff, width)
    -- Label acima
    local label = parent:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    label:SetPoint("TOPLEFT", parent, "TOPLEFT", xoff, yoff)
    label:SetText("|cff66ccffTamanho da janela:|r")

    local slider = CreateFrame("Slider", "EnglishLinksScaleSlider", parent, "OptionsSliderTemplate")
    slider:SetWidth(width)
    slider:SetHeight(16)
    slider:SetPoint("TOPLEFT", parent, "TOPLEFT", xoff, yoff - 18)
    slider:SetMinMaxValues(0.6, 1.6)
    slider:SetValueStep(0.05)
    slider:SetObeyStepOnDrag(true)
    slider:SetValue(EL_Config.get("hudScale") or 1.0)

    -- Labels min/max do template
    local low  = _G[slider:GetName() .. "Low"]
    local high = _G[slider:GetName() .. "High"]
    local text = _G[slider:GetName() .. "Text"]
    if low  then low:SetText("60%")  end
    if high then high:SetText("160%") end
    if text then text:SetText(math.floor((EL_Config.get("hudScale") or 1.0) * 100) .. "%") end

    slider:SetScript("OnValueChanged", function(self, val)
        -- Arredondar para step
        val = math.floor(val / 0.05 + 0.5) * 0.05
        EL_Config.set("hudScale", val)
        if text then text:SetText(math.floor(val * 100) .. "%") end
        applyScale()
    end)

    return slider
end

local function createPanel()
    if panel then panel:Show(); return end

    panel = CreateFrame("Frame", "EnglishLinksConfigPanel", UIParent, "BackdropTemplate")
    panel:SetSize(370, 330)
    panel:SetPoint("CENTER")
    panel:SetFrameStrata("DIALOG")
    panel:SetMovable(true)
    panel:EnableMouse(true)
    panel:RegisterForDrag("LeftButton")
    panel:SetScript("OnDragStart", panel.StartMoving)
    panel:SetScript("OnDragStop",  panel.StopMovingOrSizing)

    -- Fundo totalmente preto
    panel:SetBackdrop({
        bgFile   = "Interface\\Buttons\\WHITE8X8",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        tile = true, tileSize = 8, edgeSize = 32,
        insets = { left = 11, right = 12, top = 12, bottom = 11 },
    })
    panel:SetBackdropColor(0, 0, 0, 1)
    panel:SetBackdropBorderColor(0.4, 0.4, 0.5, 1)

    -- Escala salva
    panel:SetScale(EL_Config.get("hudScale") or 1.0)

    -- ---- Icone ----
    local iconTex = panel:CreateTexture(nil, "ARTWORK")
    iconTex:SetSize(52, 52)
    iconTex:SetPoint("TOPLEFT", panel, "TOPLEFT", 18, -16)
    iconTex:SetTexture("Interface\\AddOns\\EnglishLinks\\icon")

    -- ---- Titulo ----
    local title = panel:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOPLEFT", iconTex, "TOPRIGHT", 10, -2)
    title:SetText("|cff66ccff" .. ADDON_NAME .. "|r")

    local ver = panel:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    ver:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -3)
    ver:SetText("|cffaaaaaa v" .. VERSION .. "|r")

    local auth = panel:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    auth:SetPoint("TOPLEFT", ver, "BOTTOMLEFT", 0, -2)
    auth:SetText("|cffffd100por " .. AUTHOR .. "|r")

    -- ---- Separador 1 ----
    local sep1 = panel:CreateTexture(nil, "ARTWORK")
    sep1:SetSize(336, 1)
    sep1:SetPoint("TOPLEFT", panel, "TOPLEFT", 17, -90)
    sep1:SetColorTexture(0.25, 0.25, 0.35, 1)

    -- ---- Secao Chat ----
    local s1 = panel:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    s1:SetPoint("TOPLEFT", sep1, "BOTTOMLEFT", 0, -8)
    s1:SetText("|cff66ccffChat|r")

    createCheckbox(panel,
        "Links em ingles no chat",
        "Substitui nomes de itens, spells, mounts e mais\nnos canais de chat (say, yell, party, raid, guild, whisper, BN).",
        "chatEnabled", 26, -113)

    createCheckbox(panel,
        "Modo inverso",
        "Voce ve os links na lingua do seu cliente WoW.\nOs outros jogadores recebem os nomes em ingles.",
        "reverseMode", 26, -140)

    -- ---- Separador 2 ----
    local sep2 = panel:CreateTexture(nil, "ARTWORK")
    sep2:SetSize(336, 1)
    sep2:SetPoint("TOPLEFT", panel, "TOPLEFT", 17, -168)
    sep2:SetColorTexture(0.25, 0.25, 0.35, 1)

    -- ---- Secao Loot ----
    local s2 = panel:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    s2:SetPoint("TOPLEFT", sep2, "BOTTOMLEFT", 0, -8)
    s2:SetText("|cff66ccffLoot e Dungeon|r")

    createCheckbox(panel,
        "Loot, Rolls e fim de Mythic+",
        "Itens em mensagens de loot, rolls de Need/Greed\ne na janela final de Mythic+ aparecem em ingles.",
        "lootEnabled", 26, -192)

    -- ---- Separador 3 ----
    local sep3 = panel:CreateTexture(nil, "ARTWORK")
    sep3:SetSize(336, 1)
    sep3:SetPoint("TOPLEFT", panel, "TOPLEFT", 17, -220)
    sep3:SetColorTexture(0.25, 0.25, 0.35, 1)

    -- ---- Slider de escala ----
    createSlider(panel, 20, -232, 240)

    -- ---- Separador 4 ----
    local sep4 = panel:CreateTexture(nil, "ARTWORK")
    sep4:SetSize(336, 1)
    sep4:SetPoint("TOPLEFT", panel, "TOPLEFT", 17, -278)
    sep4:SetColorTexture(0.25, 0.25, 0.35, 1)

    -- ---- Dica ----
    local hint = panel:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    hint:SetPoint("TOPLEFT", sep4, "BOTTOMLEFT", 2, -8)
    hint:SetText("|cff888888/el  -  abre esta janela de configuracoes|r")

    -- ---- Botao fechar ----
    local closeBtn = CreateFrame("Button", nil, panel, "UIPanelButtonTemplate")
    closeBtn:SetSize(90, 24)
    closeBtn:SetPoint("BOTTOMRIGHT", panel, "BOTTOMRIGHT", -16, 12)
    closeBtn:SetText("Fechar")
    closeBtn:SetScript("OnClick", function() panel:Hide() end)

    -- ---- Botao redefinir ----
    local resetBtn = CreateFrame("Button", nil, panel, "UIPanelButtonTemplate")
    resetBtn:SetSize(90, 24)
    resetBtn:SetPoint("BOTTOMLEFT", panel, "BOTTOMLEFT", 16, 12)
    resetBtn:SetText("Redefinir")
    resetBtn:SetScript("OnClick", function()
        for k, v in pairs(defaults) do EL_Config.set(k, v) end
        panel:Hide()
        panel = nil
        createPanel()
        print("|cff66ccffEnglish Links|r configuracoes redefinidas.")
    end)

    tinsert(UISpecialFrames, "EnglishLinksConfigPanel")
    panel:Show()
end

EL_Config.openPanel = createPanel

-- Inicializar config
local initFrame = CreateFrame("Frame")
initFrame:RegisterEvent("ADDON_LOADED")
initFrame:SetScript("OnEvent", function(self, event, name)
    if name == "EnglishLinks" then
        initConfig()
        self:UnregisterAllEvents()
    end
end)

-- ================================================================
-- BOTAO DO MINIMAPA
-- ================================================================
local minimapBtn = nil
local mmAngle = 225

local function updateMinimapPosition()
    if not minimapBtn then return end
    local rad = math.rad(mmAngle)
    local x = cos(rad) * 80
    local y = sin(rad) * 80
    minimapBtn:SetPoint("CENTER", Minimap, "CENTER", x, y)
end

local function createMinimapButton()
    if minimapBtn then return end
    if EnglishLinksDB and EnglishLinksDB.minimapAngle then
        mmAngle = EnglishLinksDB.minimapAngle
    end

    minimapBtn = CreateFrame("Button", "EnglishLinksMinimapBtn", Minimap)
    minimapBtn:SetSize(32, 32)
    minimapBtn:SetFrameStrata("MEDIUM")
    minimapBtn:SetFrameLevel(8)

    local mmIcon = minimapBtn:CreateTexture(nil, "BACKGROUND")
    mmIcon:SetSize(24, 24)
    mmIcon:SetPoint("CENTER")
    mmIcon:SetTexture("Interface\\AddOns\\EnglishLinks\\icon_minimap")

    local border = minimapBtn:CreateTexture(nil, "OVERLAY")
    border:SetSize(32, 32)
    border:SetPoint("CENTER")
    border:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")

    updateMinimapPosition()

    minimapBtn:RegisterForDrag("LeftButton")
    minimapBtn:SetScript("OnDragStart", function(self)
        self:SetScript("OnUpdate", function(self)
            local mx, my = Minimap:GetCenter()
            local cx, cy = GetCursorPosition()
            local scale  = UIParent:GetEffectiveScale()
            cx, cy = cx / scale, cy / scale
            mmAngle = math.deg(math.atan2(cy - my, cx - mx))
            updateMinimapPosition()
        end)
    end)
    minimapBtn:SetScript("OnDragStop", function(self)
        self:SetScript("OnUpdate", nil)
        if EnglishLinksDB then EnglishLinksDB.minimapAngle = mmAngle end
    end)

    minimapBtn:SetScript("OnClick", function(self, btn)
        if btn == "LeftButton" then
            local p = _G["EnglishLinksConfigPanel"]
            if p and p:IsShown() then
                p:Hide()
            else
                createPanel()
            end
        end
    end)

    minimapBtn:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_LEFT")
        GameTooltip:SetText("|cff66ccffEnglish Links|r")
        GameTooltip:AddLine("Clique para abrir configuracoes", 0.8, 0.8, 0.8)
        GameTooltip:AddLine("Arraste para reposicionar", 0.6, 0.6, 0.6)
        GameTooltip:Show()
    end)
    minimapBtn:SetScript("OnLeave", function() GameTooltip:Hide() end)

    minimapBtn:Show()
end

local mmFrame = CreateFrame("Frame")
mmFrame:RegisterEvent("PLAYER_LOGIN")
mmFrame:SetScript("OnEvent", function(self)
    createMinimapButton()
    self:UnregisterAllEvents()
end)
