-- ChatTranslateUI.lua
--
-- Hauptmenü-Fenster (ChatTranslateMainFrame), NX-gebrandet.
-- Wird über das Minimap-Icon (Icon.lua) oder /ct menu geöffnet.
--
-- Enthält:
--   - Ein/Aus-Schalter
--   - Zielsprachen-Auswahl (automatisch Deutsch / de / en / fr / es / pt / ru)
--   - Live-Statistik (Wörterbuch-Treffer, Warteschlange, Begleitskript-Cache)
--   - Fußleiste mit Twitch-Verweis @NECBEX und Entwickler-Credit

local NX_GOLD   = { 0.910, 0.761, 0.290 }
local NX_RED    = { 0.753, 0.125, 0.165 }
local NX_BLACK  = { 0.055, 0.055, 0.063 }
local NX_TWITCH = { 0.569, 0.275, 1.000 } -- Twitch-Lila (#9146FF)
local NX_WHITE  = { 0.95, 0.95, 0.95 }
local NX_GREY   = { 0.62, 0.62, 0.62 }

local LANG_OPTIONS = {
    { value = nil,  label = "Automatisch (Deutsch)" },
    { value = "de", label = "Deutsch" },
    { value = "en", label = "Englisch" },
    { value = "fr", label = "Französisch" },
    { value = "es", label = "Spanisch" },
    { value = "pt", label = "Portugiesisch" },
    { value = "ru", label = "Russisch" },
}

local function CountTable(t)
    local n = 0
    for _ in pairs(t) do n = n + 1 end
    return n
end

-- ============================================================
-- Hauptfenster
-- ============================================================

local frame = CreateFrame("Frame", "ChatTranslateMainFrame", UIParent, "BackdropTemplate")
frame:SetSize(360, 430)
frame:SetPoint("CENTER")
frame:SetFrameStrata("DIALOG")
frame:SetMovable(true)
frame:EnableMouse(true)
frame:RegisterForDrag("LeftButton")
frame:SetScript("OnDragStart", frame.StartMoving)
frame:SetScript("OnDragStop", frame.StopMovingOrSizing)
frame:SetClampedToScreen(true)
frame:Hide()

frame:SetBackdrop({
    bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
    edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
    tile = true, tileSize = 16, edgeSize = 16,
    insets = { left = 4, right = 4, top = 4, bottom = 4 },
})
frame:SetBackdropColor(NX_BLACK[1], NX_BLACK[2], NX_BLACK[3], 0.95)
frame:SetBackdropBorderColor(NX_GOLD[1], NX_GOLD[2], NX_GOLD[3], 1)

-- Titel-Leiste
local titleBar = CreateFrame("Frame", nil, frame, "BackdropTemplate")
titleBar:SetPoint("TOPLEFT", 4, -4)
titleBar:SetPoint("TOPRIGHT", -4, -4)
titleBar:SetHeight(34)
titleBar:SetBackdrop({ bgFile = "Interface\\Buttons\\WHITE8x8" })
titleBar:SetBackdropColor(NX_RED[1], NX_RED[2], NX_RED[3], 0.5)
titleBar:EnableMouse(true)
titleBar:RegisterForDrag("LeftButton")
titleBar:SetScript("OnDragStart", function() frame:StartMoving() end)
titleBar:SetScript("OnDragStop", function() frame:StopMovingOrSizing() end)

local title = titleBar:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
title:SetPoint("LEFT", 12, 0)
title:SetText("ChatTranslate")
title:SetTextColor(NX_GOLD[1], NX_GOLD[2], NX_GOLD[3])

local versionText = titleBar:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall")
versionText:SetPoint("RIGHT", -32, 0)
versionText:SetText("v" .. (GetAddOnMetadata and GetAddOnMetadata("ChatTranslate", "Version") or "1.3.0"))

local closeBtn = CreateFrame("Button", nil, titleBar, "UIPanelCloseButton")
closeBtn:SetPoint("RIGHT", -2, 0)
closeBtn:SetScript("OnClick", function() frame:Hide() end)

-- ============================================================
-- Ein/Aus-Schalter
-- ============================================================

local enableCheck = CreateFrame("CheckButton", "ChatTranslateEnableCheck", frame, "UICheckButtonTemplate")
enableCheck:SetPoint("TOPLEFT", 16, -50)
_G["ChatTranslateEnableCheckText"]:SetText("Übersetzung aktiviert")
_G["ChatTranslateEnableCheckText"]:SetTextColor(NX_WHITE[1], NX_WHITE[2], NX_WHITE[3])
enableCheck:SetScript("OnClick", function(self)
    ChatTranslateDB.enabled = self:GetChecked()
end)

-- ============================================================
-- Zielsprache
-- ============================================================

local langLabel = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
langLabel:SetPoint("TOPLEFT", 16, -85)
langLabel:SetText("Zielsprache:")
langLabel:SetTextColor(NX_GOLD[1], NX_GOLD[2], NX_GOLD[3])

local langDropdown = CreateFrame("Frame", "ChatTranslateLangDropdown", frame, "UIDropDownMenuTemplate")
langDropdown:SetPoint("TOPLEFT", 0, -100)

local function GetLangLabel(value)
    for _, opt in ipairs(LANG_OPTIONS) do
        if opt.value == value then return opt.label end
    end
    return "Automatisch (Deutsch)"
end

local function LangDropdown_OnClick(self)
    ChatTranslateDB.targetLang = self.value
    UIDropDownMenu_SetSelectedValue(langDropdown, self.value)
    UIDropDownMenu_SetText(langDropdown, GetLangLabel(self.value))
end

local function LangDropdown_Initialize(self, level)
    for _, opt in ipairs(LANG_OPTIONS) do
        local info = UIDropDownMenu_CreateInfo()
        info.text = opt.label
        info.value = opt.value
        info.func = LangDropdown_OnClick
        info.checked = (ChatTranslateDB.targetLang == opt.value)
        UIDropDownMenu_AddButton(info, level)
    end
end

UIDropDownMenu_Initialize(langDropdown, LangDropdown_Initialize)
UIDropDownMenu_SetWidth(langDropdown, 220)

-- ============================================================
-- Statistik (Body)
-- ============================================================

local statsHeader = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
statsHeader:SetPoint("TOPLEFT", 16, -150)
statsHeader:SetText("Statistik:")
statsHeader:SetTextColor(NX_GOLD[1], NX_GOLD[2], NX_GOLD[3])

local statsBody = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
statsBody:SetPoint("TOPLEFT", 16, -170)
statsBody:SetJustifyH("LEFT")
statsBody:SetWidth(320)
statsBody:SetTextColor(NX_WHITE[1], NX_WHITE[2], NX_WHITE[3])

local dictWordCount = frame:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall")
dictWordCount:SetPoint("TOPLEFT", 16, -260)
dictWordCount:SetJustifyH("LEFT")
dictWordCount:SetWidth(320)

local function RefreshStats()
    statsBody:SetFormattedText(
        "Wörterbuch-Treffer: %d\nWarteschlange (unübersetzt): %d\nBegleitskript-Cache: %d",
        ChatTranslateDB.dictHits or 0,
        CountTable(ChatTranslateDB.queue or {}),
        CountTable(ChatTranslateDB.translations or {})
    )
    local wordCount = (CT_Dictionary and CT_Dictionary.words) and #CT_Dictionary.words or 0
    dictWordCount:SetFormattedText("%d Einträge geladen · en/de/fr/es/pt/ru", wordCount)
end

-- ============================================================
-- Warteschlange leeren
-- ============================================================

local clearBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
clearBtn:SetSize(160, 22)
clearBtn:SetPoint("TOPLEFT", 16, -285)
clearBtn:SetText("Warteschlange leeren")
clearBtn:SetScript("OnClick", function()
    ChatTranslateDB.queue = {}
    RefreshStats()
end)

-- ============================================================
-- Trennlinie über der Fußleiste
-- ============================================================

local divider = frame:CreateTexture(nil, "ARTWORK")
divider:SetHeight(1)
divider:SetPoint("BOTTOMLEFT", 12, 46)
divider:SetPoint("BOTTOMRIGHT", -12, 46)
divider:SetColorTexture(NX_GOLD[1], NX_GOLD[2], NX_GOLD[3], 0.4)

-- ============================================================
-- Fußleiste: Twitch-Verweis, @NECBEX, Entwickler-Credit
-- ============================================================

local footer = CreateFrame("Frame", nil, frame)
footer:SetPoint("BOTTOMLEFT", 4, 4)
footer:SetPoint("BOTTOMRIGHT", -4, 4)
footer:SetHeight(38)

-- Twitch-"Icon" (stilisiertes Kästchen in Twitch-Lila, kein Original-Logo-Asset)
local twitchBtn = CreateFrame("Button", nil, footer, "BackdropTemplate")
twitchBtn:SetSize(22, 22)
twitchBtn:SetPoint("LEFT", 6, 0)
twitchBtn:SetBackdrop({
    bgFile = "Interface\\Buttons\\WHITE8x8",
    edgeFile = "Interface\\Buttons\\WHITE8x8",
    edgeSize = 1,
})
twitchBtn:SetBackdropColor(NX_TWITCH[1], NX_TWITCH[2], NX_TWITCH[3], 1)
twitchBtn:SetBackdropBorderColor(NX_GOLD[1], NX_GOLD[2], NX_GOLD[3], 0.8)

local twitchGlyph = twitchBtn:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
twitchGlyph:SetPoint("CENTER", 0, 0)
twitchGlyph:SetText("tv")
twitchGlyph:SetTextColor(1, 1, 1)

StaticPopupDialogs["CHATTRANSLATE_TWITCH_LINK"] = {
    text = "Twitch-Kanal von NECBEX (Strg+C zum Kopieren):",
    button1 = "Schließen",
    hasEditBox = true,
    editBoxWidth = 260,
    OnShow = function(self)
        self.editBox:SetText("https://twitch.tv/necbex")
        self.editBox:HighlightText()
        self.editBox:SetFocus()
    end,
    EditBoxOnEscapePressed = function(self) self:GetParent():Hide() end,
    timeout = 0,
    whileDead = true,
    hideOnEscape = true,
    preferredIndex = 3,
}

twitchBtn:SetScript("OnClick", function()
    StaticPopup_Show("CHATTRANSLATE_TWITCH_LINK")
end)
twitchBtn:SetScript("OnEnter", function(self)
    GameTooltip:SetOwner(self, "ANCHOR_TOP")
    GameTooltip:SetText("twitch.tv/necbex", 1, 1, 1)
    GameTooltip:Show()
end)
twitchBtn:SetScript("OnLeave", function() GameTooltip:Hide() end)

local twitchHandle = footer:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
twitchHandle:SetPoint("LEFT", twitchBtn, "RIGHT", 6, 0)
twitchHandle:SetText("@NECBEX")
twitchHandle:SetTextColor(NX_TWITCH[1], NX_TWITCH[2], NX_TWITCH[3])

local devCredit = footer:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall")
devCredit:SetPoint("RIGHT", -6, 0)
devCredit:SetText("Entwickler: NECBEX")
devCredit:SetTextColor(NX_GREY[1], NX_GREY[2], NX_GREY[3])

frame:SetScript("OnShow", function()
    enableCheck:SetChecked(ChatTranslateDB.enabled)
    UIDropDownMenu_SetSelectedValue(langDropdown, ChatTranslateDB.targetLang)
    UIDropDownMenu_SetText(langDropdown, GetLangLabel(ChatTranslateDB.targetLang))
    RefreshStats()
end)

-- Für Icon.lua und Slash-Commands
ChatTranslate_ToggleMainFrame = function()
    if frame:IsShown() then
        frame:Hide()
    else
        frame:Show()
    end
end
