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

local cache = {}

local BUTTON_ORDER = {
    "NONE",
    "CHARACTER", "SPELLBOOK", "TALENTS",   "PROFESSION", "QUEST_LOG",
    "BAGS",      "COLLECTIONS", "PET_JOURNAL", "TOY_BOX",
    "FRIENDS",   "GUILD",     "GROUP_FINDER",
    "ACHIEVEMENTS", "ENCOUNTER_JOURNAL",
    "HEARTHSTONE", "SCREENSHOT", "VOLUME", "GAME_MENU",
}

local function GetLabel(k)
    local defs = ns.GameBar and ns.GameBar.BTN_DEFS or {}
    return (defs[k] and defs[k].name) or k
end

local SLOT_COUNT = (ns.GameBar and ns.GameBar.SLOT_COUNT) or 5

local function DB() return BrightQoL.gameBar end

-- ── Custom styled dropdown ─────────────────────────────────────────────────────
-- We avoid UIDropDownMenuTemplate (which has its own heavy styling) and build our own
-- minimal dark-themed dropdown consistent with BrightQoL aesthetics.

local openDropdown = nil  -- currently open menu frame

local function CloseAllDropdowns()
    if openDropdown then openDropdown:Hide(); openDropdown = nil end
end

local function CreateStyledDropdown(parent, side, slotIdx, x, y, width)
    local CYAN_R, CYAN_G, CYAN_B = 0, 207/255, 1.0

    -- Button that shows current value
    local btn = CreateFrame("Button", nil, parent, "BackdropTemplate")
    btn:SetSize(width, 22)
    btn:SetPoint("TOPLEFT", parent, "TOPLEFT", x, y)
    btn:SetBackdrop({
        bgFile   = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Buttons\\WHITE8x8",
        edgeSize = 1, insets = {left=1,right=1,top=1,bottom=1},
    })
    btn:SetBackdropColor(0.08, 0.08, 0.12, 0.95)
    btn:SetBackdropBorderColor(0, 207/255, 1.0, 0.5)

    local lbl = btn:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    lbl:SetPoint("LEFT", 6, 0)
    lbl:SetPoint("RIGHT", -20, 0)
    lbl:SetJustifyH("LEFT")
    lbl:SetTextColor(1, 1, 1, 0.9)
    btn.lbl = lbl

    local arrow = btn:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    arrow:SetPoint("RIGHT", -4, 0)
    arrow:SetText("|cff00cfffv|r")
    btn.arrow = arrow

    btn:SetScript("OnEnter", function(self)
        self:SetBackdropBorderColor(1, 1, 1, 0.8)
    end)
    btn:SetScript("OnLeave", function(self)
        self:SetBackdropBorderColor(0, 207/255, 1.0, 0.5)
    end)

    -- Update display text
    local function UpdateLabel()
        local db = DB()
        local current = db[side] and db[side][slotIdx] or "NONE"
        lbl:SetText(GetLabel(current))
    end
    UpdateLabel()

    -- Dropdown menu frame
    local menu = CreateFrame("Frame", nil, UIParent, "BackdropTemplate")
    menu:SetFrameStrata("TOOLTIP")
    menu:SetWidth(width)
    menu:SetBackdrop({
        bgFile   = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Buttons\\WHITE8x8",
        edgeSize = 1, insets = {left=1,right=1,top=1,bottom=1},
    })
    menu:SetBackdropColor(0.06, 0.06, 0.10, 0.98)
    menu:SetBackdropBorderColor(0, 207/255, 1.0, 0.7)
    menu:Hide()

    local ITEM_H = 20
    local rows = {}
    for _, k in ipairs(BUTTON_ORDER) do
        local row = CreateFrame("Button", nil, menu)
        row:SetHeight(ITEM_H)
        local rtxt = row:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
        rtxt:SetPoint("LEFT", 8, 0)
        rtxt:SetPoint("RIGHT", -4, 0)
        rtxt:SetJustifyH("LEFT")
        rtxt:SetTextColor(1, 1, 1, 0.85)
        row.lbl = rtxt
        row.key = k
        row:SetScript("OnEnter", function(self) self.lbl:SetTextColor(CYAN_R, CYAN_G, CYAN_B, 1) end)
        row:SetScript("OnLeave", function(self) self.lbl:SetTextColor(1,1,1,0.85) end)
        row:SetScript("OnClick", function(self)
            DB()[side][slotIdx] = self.key
            UpdateLabel()
            if ns.GameBar and ns.GameBar.Refresh then ns.GameBar:Refresh() end
            CloseAllDropdowns()
        end)
        rows[#rows+1] = row
    end

    -- Layout rows inside menu
    menu:SetHeight(#rows * ITEM_H + 4)

    local function RefreshMenu()
        local db = DB()
        local current = db[side] and db[side][slotIdx] or "NONE"
        for idx, row in ipairs(rows) do
            row:ClearAllPoints()
            row:SetPoint("TOPLEFT", menu, "TOPLEFT", 0, -(idx-1)*ITEM_H - 2)
            row:SetWidth(width - 2)
            if row.key == current then
                row.lbl:SetText("|cff00cfff" .. GetLabel(row.key) .. "|r")
            else
                row.lbl:SetText(GetLabel(row.key))
                row.lbl:SetTextColor(1,1,1,0.85)
            end
        end
    end

    btn:SetScript("OnClick", function(self)
        if openDropdown == menu then
            CloseAllDropdowns()
            return
        end
        CloseAllDropdowns()
        RefreshMenu()
        -- Position below the button
        menu:ClearAllPoints()
        menu:SetPoint("TOPLEFT", btn, "BOTTOMLEFT", 0, -2)
        menu:Show()
        openDropdown = menu
    end)

    -- Close when clicking elsewhere
    menu:SetScript("OnHide", function() if openDropdown == menu then openDropdown = nil end end)

    return btn, UpdateLabel
end

function ns:InitGameBar()
    local p = ns.MainFrame.Content

    W:CachedPanel(cache, "gbFrame", p, function(f)
        local sf, sc = W:CreateScrollFrame(f, 1600)

        W:CreatePageHeader(sc,
            {{"GAME ", C.BLUE}, {"BAR", C.ORANGE}},
            "Floating shortcut bar with configurable buttons and clock")

        local db = DB()
        local ROW = -90

        -- Master enable area
        local killArea = CreateFrame("Frame", nil, sc, "BackdropTemplate")
        killArea:SetSize(460, 62)
        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 Game Bar", db = db, key = "enabled",
            x = 15, y = -8, isMaster = true,
            onChange = function() if ns.GameBar then ns.GameBar:UpdateVisibility() end end,
        })
        W:CreateCheckbox(killArea, {
            label = "Lock Position", db = db, key = "locked",
            x = 15, y = -38,
            template = "ChatConfigCheckButtonTemplate",
        })

        W:CreateRestoreDefaultsButton({
            moduleName = "gameBar",
            parent = sc,
            fixedParent = killArea,
            initFunc = function() ns:InitGameBar() end,
            onRestore = function()
                if cache.gbFrame then
                    cache.gbFrame:Hide()
                    cache.gbFrame:SetParent(nil)
                    cache.gbFrame = nil
                end
                if ns.GameBar then ns.GameBar:ApplySettings() end
            end,
        })

        ROW = ROW - 70  -- skip past killArea

        -- Row 2: Mouseover + Backdrop + Border
        W:CreateCheckbox(sc, {
            label = "Fade on Mouseover", db = db, key = "mouseOver",
            x = 20, y = ROW,
            onChange = function() if ns.GameBar then ns.GameBar:ApplySettings() end end,
        })
        W:CreateCheckbox(sc, {
            label = "Show Backdrop", db = db, key = "showBackdrop",
            x = 200, y = ROW,
            onChange = function() if ns.GameBar then ns.GameBar:ApplySettings() end end,
        })
        W:CreateCheckbox(sc, {
            label = "Show Border", db = db, key = "showBorder",
            x = 350, y = ROW,
            onChange = function() if ns.GameBar then ns.GameBar:ApplySettings() end end,
        })
        ROW = ROW - 30

        -- Row 3: Hide Blizzard Bar
        W:CreateCheckbox(sc, {
            label = "Hide Blizzard Menu & Bags Bar", db = db, key = "hideBlizzBar",
            x = 20, y = ROW,
            onChange = function()
                if ns.GameBar then ns.GameBar:ApplyBlizzBar() end
            end,
        })
        ROW = ROW - 30

        -- Row 4: Border Color
        W:CreateColorPicker(sc, {
            label    = "Border Color",
            x = 20, y = ROW + 10,
            db       = db,
            rKey     = "borderColorR", gKey = "borderColorG", bKey = "borderColorB", classColorKey = "borderUseClassColor",
            onChange = function() if ns.GameBar then ns.GameBar:ApplySettings() end end,
        })
        ROW = ROW - 30

        -- Row 4: Opacity slider (full width)
        W:CreateSlider(sc, {
            label = "Bar Opacity", db = db, key = "alpha",
            min = 0.1, max = 1.0, step = 0.05,
            x = 20, y = ROW, width = 250,
            onChange = function() if ns.GameBar then ns.GameBar:ApplySettings() end end,
        })
        ROW = ROW - 55

        -- ── Clock ──────────────────────────────────────────────────────────────
        W:CreateSectionHeader(sc, "Clock", ROW)
        ROW = ROW - 30

        W:CreateCheckbox(sc, {
            label = "Local Time", db = db, key = "localTime",
            x = 20, y = ROW,
            onChange = function() if ns.GameBar then ns.GameBar:Refresh() end end,
        })
        W:CreateCheckbox(sc, {
            label = "24-Hour Format", db = db, key = "twentyFour",
            x = 200, y = ROW,
            onChange = function() if ns.GameBar then ns.GameBar:Refresh() end end,
        })
        ROW = ROW - 36

        -- ── Appearance ────────────────────────────────────────────────────────
        W:CreateSectionHeader(sc, "Appearance", ROW)
        ROW = ROW - 30

        W:CreateSlider(sc, {
            label = "Button Size", db = db, key = "buttonSize",
            min = 16, max = 48, step = 2,
            x = 15, y = ROW, width = 155,
            onChange = function() if ns.GameBar then ns.GameBar:ApplySettings() end end,
        })
        W:CreateSlider(sc, {
            label = "Spacing", db = db, key = "spacing",
            min = 0, max = 16, step = 1,
            x = 245, y = ROW, width = 155,
            onChange = function() if ns.GameBar then ns.GameBar:ApplySettings() end end,
        })
        ROW = ROW - 58

        W:CreateSlider(sc, {
            label = "Padding", db = db, key = "padding",
            min = 2, max = 20, step = 1,
            x = 15, y = ROW, width = 155,
            onChange = function() if ns.GameBar then ns.GameBar:ApplySettings() end end,
        })
        W:CreateSlider(sc, {
            label = "Clock Width", db = db, key = "clockWidth",
            min = 50, max = 160, step = 5,
            x = 245, y = ROW, width = 155,
            onChange = function() if ns.GameBar then ns.GameBar:ApplySettings() end end,
        })
        ROW = ROW - 58

        -- ── Slot sections ─────────────────────────────────────────────────────
        local function SlotSection(title, side)
            W:CreateSectionHeader(sc, title, ROW)
            ROW = ROW - 28

            local note = sc:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
            note:SetPoint("TOPLEFT", sc, "TOPLEFT", 20, ROW)
            note:SetTextColor(0.6, 0.6, 0.6, 0.8)
            note:SetText("Select '— None —' to hide a slot.")
            ROW = ROW - 26

            for i = 1, SLOT_COUNT do
                -- Label
                local lbl = sc:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
                lbl:SetPoint("TOPLEFT", sc, "TOPLEFT", 20, ROW - 9)
                lbl:SetText("Slot " .. i)
                lbl:SetTextColor(0, 207/255, 1.0, 0.9)
                -- Dropdown: top of 22px box aligned so centres match label
                CreateStyledDropdown(sc, side, i, 72, ROW - 4, 218)
                ROW = ROW - 30
            end
            ROW = ROW - 10
        end

        SlotSection("Left Side Buttons",  "left")
        SlotSection("Right Side Buttons", "right")

        sc:SetHeight(math.abs(ROW) + 40)
    end)

end
