--[[-------------------------------------------------------------------
--  BrightQoL – Config: Bloodlust Detect
--  Painel de configuração integrado no UI do BrightQoL.
-------------------------------------------------------------------]]--

local addonName, ns = ...
if not ns then return end

local W = ns.Widgets
local C = ns.COLORS

function ns:InitBloodlustDetect()
    local p   = ns.MainFrame.Content
    local BLD = ns.BloodlustDetect
    if not BLD then
        -- Módulo não carregado
        local err = p:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
        err:SetPoint("CENTER")
        err:SetText("|cffff0000BloodlustDetect module not loaded.|r")
        return
    end

    local status = BLD:GetStatus()
    local db     = status.db
    if not db then return end

    -- Build sound options list ({ text, value } format expected by CreateDropdown)
    local soundOptions = {}
    for key, entry in pairs(BLD.soundRegistry) do
        soundOptions[#soundOptions + 1] = {
            text       = entry.name,
            value      = key,
            sort_order = entry.sort_order or 5,
        }
    end
    table.sort(soundOptions, function(a, b)
        if a.sort_order ~= b.sort_order then return a.sort_order < b.sort_order end
        return a.text < b.text
    end)

    -- Build channel options list
    local channelOptions = {}
    for key, label in pairs(BLD.channelRegistry) do
        channelOptions[#channelOptions + 1] = { text = label, value = key }
    end
    table.sort(channelOptions, function(a, b) return a.text < b.text end)

    -- Use BrightQoL's scroll frame widget
    local sf, sc = W:CreateScrollFrame(p, 900)

    -- Page header
    W:CreatePageHeader(sc,
        {{"Bloodlust ", C.BLUE}, {"Detect", C.ORANGE}},
        W.Colorize("Sound alert when Bloodlust / Heroism is detected.", C.GRAY))

    local L2 = ns.Layout:New(1, { rowHeight = 44, rowStart = -120, width = 580 })

    -- ----------------------------------------------------------------
    -- MASTER ENABLE AREA
    -- ----------------------------------------------------------------
    local killArea = CreateFrame("Frame", nil, sc, "BackdropTemplate")
    killArea:SetSize(460, 50)
    killArea:SetPoint("TOPLEFT", 10, -75)
    killArea:SetBackdrop({ bgFile = [[Interface\Buttons\WHITE8x8]] })
    killArea:SetBackdropColor(0.01, 0.56, 0.91, 0.08)

    W:CreateCheckbox(killArea, {
        label       = "Enable Bloodlust detection",
        db          = db,
        key         = "enabled",
        x           = 15,
        y           = -8,
        isMaster    = true,
    })

    W:CreateRestoreDefaultsButton({
        moduleName = "bloodlust",
        parent = sc,
        fixedParent = killArea,
        yOffset = -11,
        initFunc = function() ns:InitBloodlustDetect() end,
        onRestore = function()
            if BLD then BLD:Refresh() end
        end,
    })

    -- ----------------------------------------------------------------
    -- GENERAL SECTION
    -- ----------------------------------------------------------------
    

    -- ----------------------------------------------------------------
    -- SOUND SECTION
    -- ----------------------------------------------------------------
    W:CreateSectionHeader(sc, "Sound", L2:Row(2) - 6, {x = 10})

    W:CreateDropdown(sc, {
        label   = "Alert sound",
        db      = db,
        key     = "sound",
        options = soundOptions,
        x       = 10,
        y       = L2:Row(3),
        width   = 280,
    })

    W:CreateDropdown(sc, {
        label   = "Audio channel",
        db      = db,
        key     = "channel",
        options = channelOptions,
        x       = 10,
        y       = L2:Row(4),
        width   = 280,
    })

    -- Test / Stop buttons
    local btnRow = CreateFrame("Frame", nil, sc)
    btnRow:SetSize(580, 32)
    btnRow:SetPoint("TOPLEFT", 10, L2:Row(5))

    local testBtn = W:CreateButton(btnRow, {
        text    = "Test Sound",
        width   = 130,
        height  = 28,
        onClick = function() BLD:PlayTest() end,
    })
    testBtn:SetPoint("LEFT", btnRow, "LEFT", 0, 0)

    local stopBtn = W:CreateButton(btnRow, {
        text    = "Stop Sound",
        width   = 130,
        height  = 28,
        onClick = function() BLD:StopSound() end,
    })
    stopBtn:SetPoint("LEFT", testBtn, "RIGHT", 8, 0)

    -- ----------------------------------------------------------------
    -- DEBUG SECTION
    -- ----------------------------------------------------------------
    W:CreateSectionHeader(sc, "Advanced", L2:Row(6) - 10, {x = 10})

    W:CreateCheckbox(sc, {
        label       = "Debug mode",
        db          = db,
        key         = "debug",
        x           = 10,
        y           = L2:Row(7),
        template    = "ChatConfigCheckButtonTemplate",
        description = "Print detection events to chat (for troubleshooting).",
        descWidth   = 400,
    })

    -- ----------------------------------------------------------------
    -- STATUS
    -- ----------------------------------------------------------------
    W:CreateSectionHeader(sc, "Status", L2:Row(8) - 10, {x = 10})

    local statusText = sc:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    statusText:SetPoint("TOPLEFT", 14, L2:Row(9))
    statusText:SetTextColor(0.8, 0.8, 0.8)

    local function RefreshStatus()
        local s   = BLD:GetStatus()
        local h   = string.format("%.1f%%", s.currentHaste)
        local bm  = string.format("%.1f%%", s.baselineMean)
        local det = s.db and s.db.detection or {}
        statusText:SetText(string.format(
            "|cff00cfffCurrent Haste:|r %s    |cff00cfff Baseline:|r %s\n" ..
            "|cff00cfff Ticker:|r %s    |cff00cfff Lust Active:|r %s\n" ..
            "|cff00cfff Spike threshold:|r %s    |cff00cfff Jump threshold:|r %s",
            h, bm,
            s.tickerRunning and "|cff00ff00running|r" or "|cffff4444stopped|r",
            s.lustActive    and "|cff00ff00YES|r"     or "|cffaaaaaa no|r",
            tostring(det.spike_threshold or "?"),
            tostring(det.jump_threshold  or "?")
        ))
    end

    RefreshStatus()

    -- Auto-refresh status every 1s while panel is visible
    local refreshTicker
    local function onShow() refreshTicker = C_Timer.NewTicker(1.0, RefreshStatus) end
    local function onHide() if refreshTicker then refreshTicker:Cancel(); refreshTicker = nil end end

    -- Attach to scroll frame's parent (content area) visibility
    local hook = CreateFrame("Frame", nil, p)
    hook:SetAllPoints(p)
    hook:SetScript("OnShow", onShow)
    hook:SetScript("OnHide", onHide)
end
