-------------------------
-- AiB Combat Settings Tab
-- Covers: Combat Alert + Combat Timer
-------------------------

AiB = AiB or {}
AiB.CombatSettings = {}

local FONT      = AiB.Config and AiB.Config.FONTS.HEADER  or "Fonts\\FRIZQT__.TTF"
local FONT_BODY = AiB.Config and AiB.Config.FONTS.PRIMARY or "Fonts\\ARIALN.TTF"

-- Sound-Liste (SOUNDKIT, analog zu CallToArms)
local COMBAT_SOUNDS = {
    { id = 0, name = "Kein Sound",   soundkit = nil                     },
    { id = 1, name = "Auktionshaus", soundkit = "AUCTION_WINDOW_OPEN"   },
    { id = 2, name = "Ready Check",  soundkit = "READY_CHECK"           },
    { id = 3, name = "Flüstern",     soundkit = "TELL_MESSAGE"          },
    { id = 4, name = "Raid Warning", soundkit = "RAID_WARNING"          },
    { id = 5, name = "Achievement",  soundkit = "ACHIEVEMENT_MENU_OPEN" },
    { id = 9, name = "PvP Start",    soundkit = "PVP_ENTER_QUEUE"       },
}

-- TTS-Stimmen (lazy-loaded)
local ttsVoiceList = nil
local function GetTTSVoices()
    if ttsVoiceList then return ttsVoiceList end
    ttsVoiceList = { { id = 0, name = "Standard" } }
    if C_VoiceChat and C_VoiceChat.GetNumTTSVoices then
        for i = 0, C_VoiceChat.GetNumTTSVoices() - 1 do
            local info = C_VoiceChat.GetTTSVoiceInfo(i)
            if info then
                table.insert(ttsVoiceList, { id = i, name = info.name or ("Stimme " .. i) })
            end
        end
    end
    return ttsVoiceList
end

local function GetVoiceIndex(voiceID)
    local voices = GetTTSVoices()
    for i, v in ipairs(voices) do
        if v.id == voiceID then return i end
    end
    return 1
end

-------------------------
-- UI-Helfer
-------------------------
local function Header(parent, text, x, y, size)
    local fs = parent:CreateFontString(nil, "OVERLAY")
    fs:SetFont(FONT, size or 14, "OUTLINE")
    fs:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
    fs:SetText(text)
    fs:SetTextColor(1, 0.8, 0, 1)
    return fs
end

local function SubHeader(parent, text, x, y)
    local fs = parent:CreateFontString(nil, "OVERLAY")
    fs:SetFont(FONT, 13, "OUTLINE")
    fs:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
    fs:SetText(text)
    fs:SetTextColor(1, 0.5, 0, 1)
    return fs
end

local function Label(parent, text, x, y)
    local fs = parent:CreateFontString(nil, "OVERLAY")
    fs:SetFont(FONT_BODY, 11)
    fs:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
    fs:SetTextColor(0.9, 0.9, 0.9, 1)
    fs:SetText(text)
    return fs
end

local function InfoText(parent, text, x, y)
    local fs = parent:CreateFontString(nil, "OVERLAY")
    fs:SetFont(FONT_BODY, 11)
    fs:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
    fs:SetPoint("TOPRIGHT", parent, "TOPRIGHT", -20, y)
    fs:SetJustifyH("LEFT")
    fs:SetWordWrap(true)
    fs:SetText(text)
    fs:SetTextColor(0.6, 0.6, 0.6, 1)
    return fs
end

local function Separator(parent, y)
    local line = parent:CreateTexture(nil, "ARTWORK")
    line:SetHeight(1)
    line:SetPoint("TOPLEFT",  parent, "TOPLEFT",  20, y)
    line:SetPoint("TOPRIGHT", parent, "TOPRIGHT", -20, y)
    line:SetColorTexture(0.6, 0, 0, 0.5)
end

local function CreateColorButton(parent, x, y, getR, getG, getB, setFunc, onRefresh)
    local btn = CreateFrame("Button", nil, parent, "BackdropTemplate")
    btn:SetSize(24, 24)
    btn:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
    btn:SetBackdrop({ bgFile = "Interface\\Buttons\\WHITE8x8", edgeFile = "Interface\\Buttons\\WHITE8x8", edgeSize = 1 })
    btn:SetBackdropBorderColor(0.5, 0.5, 0.5, 1)
    local swatch = btn:CreateTexture(nil, "ARTWORK")
    swatch:SetPoint("TOPLEFT", 2, -2); swatch:SetPoint("BOTTOMRIGHT", -2, 2)
    swatch:SetColorTexture(1, 1, 1)
    local function Upd() swatch:SetVertexColor(getR(), getG(), getB()) end; Upd()
    local hl = btn:CreateTexture(nil, "HIGHLIGHT"); hl:SetAllPoints(); hl:SetColorTexture(1, 1, 1, 0.3)
    btn:SetScript("OnClick", function()
        local r, g, b = getR(), getG(), getB()
        ColorPickerFrame:SetupColorPickerAndShow({
            r = r, g = g, b = b, hasOpacity = false,
            swatchFunc  = function() local nr,ng,nb = ColorPickerFrame:GetColorRGB(); setFunc(nr,ng,nb); Upd(); if onRefresh then onRefresh() end end,
            cancelFunc  = function() setFunc(r,g,b); Upd(); if onRefresh then onRefresh() end end,
        })
    end)
    AiB.Utils:AddTooltip(btn, "Farbe ändern", nil, "ANCHOR_RIGHT")
    return btn
end

local function CreateEditBox(parent, x, y, width, default, maxLen, onChanged)
    local eb = CreateFrame("EditBox", nil, parent, "BackdropTemplate")
    eb:SetSize(width, 24)
    eb:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
    eb:SetBackdrop({ bgFile="Interface\\Buttons\\WHITE8x8", edgeFile="Interface\\Buttons\\WHITE8x8", edgeSize=1 })
    eb:SetBackdropColor(0.05, 0.05, 0.05, 1)
    eb:SetBackdropBorderColor(0.4, 0.4, 0.4, 1)
    eb:SetFontObject("GameFontHighlightSmall")
    eb:SetAutoFocus(false); eb:SetTextInsets(6,6,0,0)
    eb:SetMaxLetters(maxLen or 50); eb:SetText(default or "")
    eb:SetScript("OnEnterPressed", function(s) s:ClearFocus() end)
    eb:SetScript("OnEscapePressed", function(s) s:ClearFocus() end)
    if onChanged then eb:SetScript("OnEditFocusLost", function(s) onChanged(s:GetText()) end) end
    return eb
end

-- Sound-Dropdown + Testen-Button
-- Kompletter Audio-Abschnitt: Modus + Sound + TTS
-- Gibt neues yOffset zurück
local function CreateAudioSection(parent, x, y, db, prefix, onRefresh)
    -- Modus-Dropdown
    Label(parent, "Audio:", x, y)

    local MODES = {
        { text = "Kein Audio",     value = "none"  },
        { text = "Sound",          value = "sound" },
        { text = "Text-to-Speech", value = "tts"   },
    }

    local modeDD = CreateFrame("Frame", nil, parent, "UIDropDownMenuTemplate")
    modeDD:SetPoint("TOPLEFT", parent, "TOPLEFT", x + 55, y + 8)
    UIDropDownMenu_SetWidth(modeDD, 130)

    local function GetMode() return db[prefix .. "AudioMode"] or "none" end
    local function SetModeText(val)
        for _, m in ipairs(MODES) do
            if m.value == val then UIDropDownMenu_SetText(modeDD, m.text); return end
        end
    end

    -- Beide Blöcke starten auf der gleichen Y-Position (sectionY).
    -- Nur einer ist sichtbar – daher kein Versatz nötig.
    local sectionY = y - 36

    -- ── Sound-Block ──
    local soundLbl      = Label(parent, "Sound:", x, sectionY)
    local soundDD       = CreateFrame("Frame", nil, parent, "UIDropDownMenuTemplate")
    soundDD:SetPoint("TOPLEFT", parent, "TOPLEFT", x + 55, sectionY + 8)
    UIDropDownMenu_SetWidth(soundDD, 160)

    local function GetSoundId()  return db[prefix .. "SoundId"] or 0 end
    local function SetSoundText(id)
        for _, s in ipairs(COMBAT_SOUNDS) do
            if s.id == id then UIDropDownMenu_SetText(soundDD, s.name); return end
        end
    end
    UIDropDownMenu_Initialize(soundDD, function(self, level)
        local info = UIDropDownMenu_CreateInfo()
        for _, s in ipairs(COMBAT_SOUNDS) do
            info.text    = s.name
            info.value   = s.id
            info.checked = (GetSoundId() == s.id)
            info.func    = function(btn)
                db[prefix .. "SoundId"] = btn.value
                SetSoundText(btn.value)
                CloseDropDownMenus()
            end
            UIDropDownMenu_AddButton(info, level)
        end
    end)
    SetSoundText(GetSoundId())

    local soundTestBtn = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    soundTestBtn:SetSize(80, 22)
    soundTestBtn:SetPoint("LEFT", soundDD, "RIGHT", 4, -2)
    soundTestBtn:SetText("Testen")
    soundTestBtn:SetScript("OnClick", function()
        for _, s in ipairs(COMBAT_SOUNDS) do
            if s.id == GetSoundId() then
                if s.soundkit and SOUNDKIT[s.soundkit] then
                    PlaySound(SOUNDKIT[s.soundkit], "Master")
                end
                return
            end
        end
    end)

    -- ── TTS-Block (gleiche sectionY) ──
    local ttsNachrichtLbl = Label(parent, "Nachricht:", x, sectionY)
    local ttsBox = CreateEditBox(parent, x + 80, sectionY, 180,
        db[prefix .. "TtsMessage"] or (prefix == "enter" and "Combat" or "Safe"), 50,
        function(val)
            val = val ~= "" and val or (prefix == "enter" and "Combat" or "Safe")
            db[prefix .. "TtsMessage"] = val
        end)

    local ttsStimmeLbl = Label(parent, "Stimme:", x, sectionY - 34)
    local voices     = GetTTSVoices()
    local voiceItems = {}
    for _, v in ipairs(voices) do table.insert(voiceItems, { text = v.name, value = v.id }) end
    local voiceDD = AiB.Utils:CreateDropdown(parent, 160, voiceItems,
        GetVoiceIndex(db[prefix .. "TtsVoiceID"] or 0),
        function(val) db[prefix .. "TtsVoiceID"] = val end)
    voiceDD:SetPoint("TOPLEFT", parent, "TOPLEFT", x + 60, sectionY - 26)

    local ttsVolLbl   = Label(parent, "Lautstärke:", x, sectionY - 72)
    local volValLbl   = Label(parent, (db[prefix .. "TtsVolume"] or 50) .. "%", x + 260, sectionY - 72)
    local volSlider   = AiB.Utils:CreateSlider(parent, 0, 100, 5,
        db[prefix .. "TtsVolume"] or 50,
        function(val) db[prefix .. "TtsVolume"] = val; volValLbl:SetText(val .. "%") end)
    volSlider:SetWidth(200)
    volSlider:SetPoint("TOPLEFT", parent, "TOPLEFT", x + 85, sectionY - 90)

    local ttsRateLbl  = Label(parent, "Geschwindigkeit:", x, sectionY - 120)
    local rateValLbl  = Label(parent, tostring(db[prefix .. "TtsRate"] or 0), x + 260, sectionY - 120)
    local rateSlider  = AiB.Utils:CreateSlider(parent, -10, 10, 1,
        db[prefix .. "TtsRate"] or 0,
        function(val) db[prefix .. "TtsRate"] = val; rateValLbl:SetText(val) end)
    rateSlider:SetWidth(200)
    rateSlider:SetPoint("TOPLEFT", parent, "TOPLEFT", x + 115, sectionY - 138)

    -- Höhe des TTS-Blocks: 34 + 38 + 48 + 48 = 168px → return sectionY - 168
    local soundElements = { soundLbl, soundDD, soundTestBtn }
    local ttsElements   = { ttsNachrichtLbl, ttsBox, ttsStimmeLbl, voiceDD,
                             ttsVolLbl, volValLbl, volSlider,
                             ttsRateLbl, rateValLbl, rateSlider }

    local function Refresh()
        local mode = GetMode()
        for _, el in ipairs(soundElements) do el:SetShown(mode == "sound") end
        for _, el in ipairs(ttsElements)   do el:SetShown(mode == "tts")   end
    end
    Refresh()

    UIDropDownMenu_Initialize(modeDD, function(self, level)
        local info = UIDropDownMenu_CreateInfo()
        for _, m in ipairs(MODES) do
            info.text    = m.text
            info.value   = m.value
            info.checked = (GetMode() == m.value)
            info.func    = function(btn)
                db[prefix .. "AudioMode"] = btn.value
                SetModeText(btn.value)
                Refresh()
                CloseDropDownMenus()
                if onRefresh then onRefresh() end
            end
            UIDropDownMenu_AddButton(info, level)
        end
    end)
    SetModeText(GetMode())

    -- Immer genug Platz für den größeren Block (TTS) reservieren
    return sectionY - 168
end

-------------------------
-- Haupt-Panel
-------------------------
function AiB.CombatSettings:AddToSettingsPanel(parent, yOffset)
    local dbA = AiB.db and AiB.db.profile and AiB.db.profile.combatAlert
    local dbT = AiB.db and AiB.db.profile and AiB.db.profile.combatTimer

    local function refreshAlert() if AiB.Combat and AiB.Combat.RefreshAlert then AiB.Combat.RefreshAlert() end end
    local function refreshTimer() if AiB.Combat and AiB.Combat.RefreshTimer then AiB.Combat.RefreshTimer() end end

    -- ═══════════════════════════════════
    --  COMBAT ALERT
    -- ═══════════════════════════════════
    Header(parent, "COMBAT ALERT", 20, yOffset, 16)
    yOffset = yOffset - 30

    if dbA then
        local alertEnableCB = AiB.Utils:CreateCheckbox(parent, "Combat Alert aktivieren",
            dbA.enabled or false, function(c) dbA.enabled = c; refreshAlert() end)
        alertEnableCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
        yOffset = yOffset - 30

        local alertUnlockCB = AiB.Utils:CreateCheckbox(parent, "Frame entsperren",
            dbA.unlock or false, function(c) dbA.unlock = c; refreshAlert() end)
        alertUnlockCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
        yOffset = yOffset - 40

        -- Kampf beginnt
        SubHeader(parent, ">>  Kampf beginnt", 20, yOffset); yOffset = yOffset - 28

        Label(parent, "Anzeigetext:", 20, yOffset)
        CreateEditBox(parent, 130, yOffset, 150, dbA.enterText or "++ Combat", 50,
            function(val) dbA.enterText = val ~= "" and val or "++ Combat"; refreshAlert() end)
        yOffset = yOffset - 32

        Label(parent, "Textfarbe:", 20, yOffset)
        CreateColorButton(parent, 110, yOffset - 2,
            function() return dbA.enterR or 0 end,
            function() return dbA.enterG or 1 end,
            function() return dbA.enterB or 0 end,
            function(r,g,b) dbA.enterR=r; dbA.enterG=g; dbA.enterB=b end, refreshAlert)
        local enterClassCB = AiB.Utils:CreateCheckbox(parent, "Klassenfarbe",
            dbA.enterUseClassColor or false, function(c) dbA.enterUseClassColor=c; refreshAlert() end)
        enterClassCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 155, yOffset)
        yOffset = yOffset - 36

        yOffset = CreateAudioSection(parent, 20, yOffset, dbA, "enter", refreshAlert)
        yOffset = yOffset - 20

        -- Kampf endet
        Separator(parent, yOffset); yOffset = yOffset - 18
        SubHeader(parent, "<<  Kampf endet", 20, yOffset); yOffset = yOffset - 28

        Label(parent, "Anzeigetext:", 20, yOffset)
        CreateEditBox(parent, 130, yOffset, 150, dbA.leaveText or "-- Combat", 50,
            function(val) dbA.leaveText = val ~= "" and val or "-- Combat"; refreshAlert() end)
        yOffset = yOffset - 32

        Label(parent, "Textfarbe:", 20, yOffset)
        CreateColorButton(parent, 110, yOffset - 2,
            function() return dbA.leaveR or 1 end,
            function() return dbA.leaveG or 0.2 end,
            function() return dbA.leaveB or 0.2 end,
            function(r,g,b) dbA.leaveR=r; dbA.leaveG=g; dbA.leaveB=b end, refreshAlert)
        local leaveClassCB = AiB.Utils:CreateCheckbox(parent, "Klassenfarbe",
            dbA.leaveUseClassColor or false, function(c) dbA.leaveUseClassColor=c; refreshAlert() end)
        leaveClassCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 155, yOffset)
        yOffset = yOffset - 36

        yOffset = CreateAudioSection(parent, 20, yOffset, dbA, "leave", refreshAlert)
        yOffset = yOffset - 20
    else
        InfoText(parent, "Combat Alert Daten nicht verfügbar – bitte /reload.", 20, yOffset)
        yOffset = yOffset - 30
    end

    -- ═══════════════════════════════════
    --  COMBAT TIMER
    -- ═══════════════════════════════════
    yOffset = yOffset - 10
    Separator(parent, yOffset); yOffset = yOffset - 20
    Header(parent, "COMBAT TIMER", 20, yOffset, 16); yOffset = yOffset - 30

    if dbT then
        local timerEnableCB = AiB.Utils:CreateCheckbox(parent, "Combat Timer aktivieren",
            dbT.enabled or false, function(c) dbT.enabled=c; refreshTimer() end)
        timerEnableCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
        yOffset = yOffset - 30

        local timerUnlockCB = AiB.Utils:CreateCheckbox(parent, "Frame entsperren",
            dbT.unlock or false, function(c) dbT.unlock=c; refreshTimer() end)
        timerUnlockCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
        yOffset = yOffset - 40

        SubHeader(parent, "Optionen", 20, yOffset); yOffset = yOffset - 28

        local instanceCB = AiB.Utils:CreateCheckbox(parent, "Nur in Instanzen",
            dbT.instanceOnly or false, function(c) dbT.instanceOnly=c; refreshTimer() end)
        instanceCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)

        local chatCB = AiB.Utils:CreateCheckbox(parent, "Kampfdauer im Chat",
            dbT.chatReport ~= false, function(c) dbT.chatReport=c; refreshTimer() end)
        chatCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 240, yOffset)
        yOffset = yOffset - 30

        local stickyCB = AiB.Utils:CreateCheckbox(parent, "Letzten Timer anzeigen (Sticky)",
            dbT.stickyTimer or false, function(c) dbT.stickyTimer=c; refreshTimer() end)
        stickyCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
        yOffset = yOffset - 40

        SubHeader(parent, "Darstellung", 20, yOffset); yOffset = yOffset - 28

        local hidePrefixCB = AiB.Utils:CreateCheckbox(parent, "Prefix \"COMBAT:\" ausblenden",
            dbT.hidePrefix or false, function(c) dbT.hidePrefix=c; refreshTimer() end)
        hidePrefixCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)

        local showBgCB = AiB.Utils:CreateCheckbox(parent, "Hintergrund anzeigen",
            dbT.showBackground or false, function(c) dbT.showBackground=c; refreshTimer() end)
        showBgCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 240, yOffset)
        yOffset = yOffset - 36

        Label(parent, "Timer-Farbe:", 20, yOffset)
        CreateColorButton(parent, 110, yOffset - 2,
            function() return dbT.colorR or 1 end,
            function() return dbT.colorG or 0.8 end,
            function() return dbT.colorB or 0 end,
            function(r,g,b) dbT.colorR=r; dbT.colorG=g; dbT.colorB=b end, refreshTimer)
        local timerClassCB = AiB.Utils:CreateCheckbox(parent, "Klassenfarbe",
            dbT.useClassColor or false, function(c) dbT.useClassColor=c; refreshTimer() end)
        timerClassCB:SetPoint("TOPLEFT", parent, "TOPLEFT", 155, yOffset)
        yOffset = yOffset - 36

        Label(parent, "Eigener Text:", 20, yOffset)
        Label(parent, "{m} = Minuten  {s} = Sekunden  {cs} = Hundertstel", 120, yOffset):SetTextColor(0.6,0.6,0.6,1)
        yOffset = yOffset - 20
        CreateEditBox(parent, 20, yOffset, 220, dbT.combatText or "", 60,
            function(val) dbT.combatText = val ~= "" and val or nil; refreshTimer() end)
        yOffset = yOffset - 40

        local hint = parent:CreateFontString(nil, "OVERLAY")
        hint:SetFont(FONT_BODY, 11)
        hint:SetPoint("TOPLEFT", parent, "TOPLEFT", 20, yOffset)
        hint:SetPoint("TOPRIGHT", parent, "TOPRIGHT", -20, yOffset)
        hint:SetJustifyH("LEFT"); hint:SetWordWrap(true)
        hint:SetText("Frame entsperren um ihn zu positionieren. Resize-Handle unten rechts zum Skalieren.")
        hint:SetTextColor(1, 0.6, 0.2, 1)
        yOffset = yOffset - 40
    else
        InfoText(parent, "Combat Timer Daten nicht verfügbar – bitte /reload.", 20, yOffset)
        yOffset = yOffset - 30
    end

    return yOffset
end
