local addonName, _ns = ...
local AC = _G.ArenaCore
if not AC then return end

local V = AC.Vanity

local function ApplyAtlasCardBg(frame)
    if not frame then return end

    local COLORS = AC.COLORS or {}

    local fill = frame:CreateTexture(nil, "BACKGROUND", nil, 2)
    local bgColor = COLORS.HEADER_BG or {0.18, 0.18, 0.18, 1}
    fill:SetColorTexture(bgColor[1], bgColor[2], bgColor[3], bgColor[4] or 1)
    fill:SetPoint("TOPLEFT", 1, -1)
    fill:SetPoint("BOTTOMRIGHT", -1, 1)
    frame.__acFill = fill
    frame.__acFillIsGroupBox = true

    local borderFrame = CreateFrame("Frame", nil, frame)
    borderFrame:SetAllPoints(frame)

    local uniqueLevel = frame:GetFrameLevel() + 1
    if frame:GetParent() then
        uniqueLevel = uniqueLevel + (frame:GetFrameLevel() % 3)
    end
    borderFrame:SetFrameLevel(uniqueLevel)

    local purpleTop = borderFrame:CreateTexture(nil, "BORDER", nil, 1)
    purpleTop:SetColorTexture(0.545, 0.271, 1.000, 1)
    purpleTop:SetPoint("TOPLEFT", frame, "TOPLEFT", 0, 0)
    purpleTop:SetPoint("TOPRIGHT", frame, "TOPRIGHT", 0, 0)
    purpleTop:SetHeight(1)
    if purpleTop.SetSnapToPixelGrid then purpleTop:SetSnapToPixelGrid(true) end
    if purpleTop.SetTexelSnappingBias then purpleTop:SetTexelSnappingBias(0) end

    local grayTop = borderFrame:CreateTexture(nil, "BORDER", nil, 0)
    grayTop:SetColorTexture(0.278, 0.278, 0.278, 0.9)
    grayTop:SetPoint("TOPLEFT", frame, "TOPLEFT", 0, -1)
    grayTop:SetPoint("TOPRIGHT", frame, "TOPRIGHT", 0, -1)
    grayTop:SetHeight(1)

    local grayBottom = borderFrame:CreateTexture(nil, "BORDER", nil, 0)
    grayBottom:SetColorTexture(0.278, 0.278, 0.278, 0.9)
    grayBottom:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 0, 0)
    grayBottom:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", 0, 0)
    grayBottom:SetHeight(1)

    local grayLeft = borderFrame:CreateTexture(nil, "BORDER", nil, 0)
    grayLeft:SetColorTexture(0.278, 0.278, 0.278, 0.9)
    grayLeft:SetPoint("TOPLEFT", frame, "TOPLEFT", 0, 0)
    grayLeft:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 0, 0)
    grayLeft:SetWidth(1)

    local grayRight = borderFrame:CreateTexture(nil, "BORDER", nil, 0)
    grayRight:SetColorTexture(0.278, 0.278, 0.278, 0.9)
    grayRight:SetPoint("TOPRIGHT", frame, "TOPRIGHT", 0, 0)
    grayRight:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", 0, 0)
    grayRight:SetWidth(1)

    frame.__acBorderFrame = borderFrame
end

local function CreateModalBase(frameName, width, height)
    local f = CreateFrame("Frame", frameName, UIParent, "BackdropTemplate")
    f:SetSize(width, height)
    f:SetPoint("CENTER")
    f:SetFrameStrata("FULLSCREEN_DIALOG")
    f:SetFrameLevel(9999)

    f:SetBackdrop({
        bgFile = "Interface/Tooltips/UI-Tooltip-Background",
        edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
        edgeSize = 14,
        insets = { left = 3, right = 3, top = 3, bottom = 3 }
    })
    f:SetBackdropColor(0, 0, 0, 0.9)

    local overlay = f:CreateTexture(nil, "BORDER")
    overlay:SetAllPoints()
    overlay:SetColorTexture(0, 0, 0, 0.35)

    return f
end

local function ShowActiveProfileError()
    local popup = CreateModalBase("ArenaCoreActiveProfileError", 360, 130)

    local title = popup:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOP", 0, -16)
    title:SetText("Cannot Delete Active Profile")

    local msg = popup:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    msg:SetPoint("TOP", title, "BOTTOM", 0, -12)
    msg:SetWidth(320)
    msg:SetJustifyH("CENTER")
    msg:SetText("Switch to another profile first, then try deleting again.")

    local ok = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
    ok:SetSize(120, 26)
    ok:SetPoint("BOTTOM", 0, 14)
    ok:SetText("OK")
    ok:SetScript("OnClick", function() popup:Hide() end)

    popup:Show()
end

local function ShowReloadConfirmation(profileName)
    local popup = CreateModalBase("ArenaCoreProfileReloadPopup", 420, 160)

    local title = popup:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOP", 0, -16)
    title:SetText("Reload Required")

    local msg = popup:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    msg:SetPoint("TOP", title, "BOTTOM", 0, -12)
    msg:SetWidth(380)
    msg:SetJustifyH("CENTER")
    msg:SetText("Profile switched to '" .. tostring(profileName) .. "'.\nReload your UI to fully apply it.")

    local reloadBtn = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
    reloadBtn:SetSize(140, 26)
    reloadBtn:SetPoint("BOTTOM", -75, 14)
    reloadBtn:SetText("Reload")
    reloadBtn:SetScript("OnClick", function()
        popup:Hide()
        ReloadUI()
    end)

    local laterBtn = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
    laterBtn:SetSize(140, 26)
    laterBtn:SetPoint("BOTTOM", 75, 14)
    laterBtn:SetText("Later")
    laterBtn:SetScript("OnClick", function() popup:Hide() end)

    popup:Show()
end

local function ShowDeleteConfirmation(profileName, onConfirm)
    local popup = CreateModalBase("ArenaCoreDeleteProfilePopup", 430, 180)

    local title = popup:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOP", 0, -16)
    title:SetText("Delete Profile?")

    local msg = popup:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    msg:SetPoint("TOP", title, "BOTTOM", 0, -12)
    msg:SetWidth(390)
    msg:SetJustifyH("CENTER")
    msg:SetText("Are you sure you want to delete '" .. tostring(profileName) .. "'?\nThis cannot be undone.")

    local deleteBtn = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
    deleteBtn:SetSize(140, 26)
    deleteBtn:SetPoint("BOTTOM", -75, 14)
    deleteBtn:SetText("Delete")
    deleteBtn:SetScript("OnClick", function()
        popup:Hide()
        if onConfirm then onConfirm() end
    end)

    local cancelBtn = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
    cancelBtn:SetSize(140, 26)
    cancelBtn:SetPoint("BOTTOM", 75, 14)
    cancelBtn:SetText("Cancel")
    cancelBtn:SetScript("OnClick", function() popup:Hide() end)

    popup:Show()
end

local function ShowImportWindow(onImported)
    local window = CreateModalBase("ArenaCoreImportWindow", 520, 420)

    window:SetBackdropColor(0, 0, 0, 0.92)

    local title = window:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOPLEFT", 16, -14)
    title:SetText("Import Profile")
    title:SetTextColor(1, 1, 1, 1)

    local nameLabel = window:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    nameLabel:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -12)
    nameLabel:SetText("Profile Name")
    nameLabel:SetTextColor(1, 1, 1, 1)

    local nameBox = CreateFrame("EditBox", nil, window, "InputBoxTemplate")
    nameBox:SetAutoFocus(false)
    nameBox:SetSize(250, 24)
    nameBox:SetPoint("TOPLEFT", nameLabel, "BOTTOMLEFT", -6, -6)
    nameBox:SetText("Imported")
    nameBox:HighlightText()

    local codeLabel = window:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    codeLabel:SetPoint("TOPLEFT", nameBox, "BOTTOMLEFT", 6, -10)
    codeLabel:SetText("Paste Import String")
    codeLabel:SetTextColor(1, 1, 1, 1)

    local inputScroll = CreateFrame("ScrollFrame", nil, window, "InputScrollFrameTemplate")
    inputScroll:SetPoint("TOPLEFT", codeLabel, "BOTTOMLEFT", -6, -8)
    inputScroll:SetPoint("BOTTOMRIGHT", window, "BOTTOMRIGHT", -32, 70)

    local edit = inputScroll.EditBox
    edit:SetAutoFocus(false)
    edit:SetText("")
    if edit.SetTextColor then
        edit:SetTextColor(1, 1, 1, 1)
    end
    edit:SetScript("OnEscapePressed", function(self) self:ClearFocus() end)

    local clickCatcher = CreateFrame("Button", nil, inputScroll)
    clickCatcher:SetAllPoints(inputScroll)
    clickCatcher:RegisterForClicks("LeftButtonDown", "RightButtonDown")
    clickCatcher:SetScript("OnMouseDown", function()
        edit:SetFocus()
        edit:SetCursorPosition(#(edit:GetText() or ""))
    end)

    local statusText = window:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    statusText:SetPoint("BOTTOMLEFT", 16, 46)
    statusText:SetText(" ")
    statusText:SetTextColor(1, 1, 1, 1)

    local importBtn
    local closeBtn
    if AC.CreateProfileStyleButton then
        importBtn = AC:CreateProfileStyleButton(window, 140, 30, "Import", "primary", 12)
        importBtn:SetPoint("BOTTOMRIGHT", -16, 14)

        closeBtn = AC:CreateProfileStyleButton(window, 140, 30, "Close", "danger", 12)
        closeBtn:SetPoint("RIGHT", importBtn, "LEFT", -10, 0)
        closeBtn:SetScript("OnClick", function() window:Hide() end)
    else
        importBtn = CreateFrame("Button", nil, window, "UIPanelButtonTemplate")
        importBtn:SetSize(140, 26)
        importBtn:SetPoint("BOTTOMRIGHT", -16, 14)
        importBtn:SetText("Import")

        closeBtn = CreateFrame("Button", nil, window, "UIPanelButtonTemplate")
        closeBtn:SetSize(140, 26)
        closeBtn:SetPoint("RIGHT", importBtn, "LEFT", -10, 0)
        closeBtn:SetText("Close")
        closeBtn:SetScript("OnClick", function() window:Hide() end)
    end

    importBtn:SetScript("OnClick", function()
        if not AC.ProfileManager then
            statusText:SetText("|cffFF0000Profile system not available|r")
            return
        end

        local profileName = tostring(nameBox:GetText() or "")
        local shareCode = tostring(edit:GetText() or "")

        local success, err = AC.ProfileManager:ImportProfile(shareCode, profileName)
        if not success then
            statusText:SetText("|cffFF0000" .. tostring(err or "Import failed") .. "|r")
            return
        end

        statusText:SetText("|cff00FF00Imported and activated!|r")
        if onImported then onImported(profileName) end
        C_Timer.After(0.15, function()
            window:Hide()
            ShowReloadConfirmation(profileName)
        end)
    end)

    window:Show()
    C_Timer.After(0, function()
        edit:SetFocus()
    end)
end

local function ShowShareProfileWindow(shareCode, profileName)
    local window = CreateModalBase("ArenaCoreShareProfileWindow", 520, 420)
    window:SetBackdropColor(0, 0, 0, 0.92)

    local title = window:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOPLEFT", 16, -14)
    title:SetText("Share Profile")
    title:SetTextColor(1, 1, 1, 1)

    local sub = window:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    sub:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -6)
    sub:SetText("Copy the code below to share your current profile.")
    sub:SetTextColor(1, 1, 1, 1)

    local nameText = window:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    nameText:SetPoint("TOPLEFT", sub, "BOTTOMLEFT", 0, -6)
    nameText:SetText("Profile: " .. tostring(profileName or ""))
    nameText:SetTextColor(1, 1, 1, 1)

    local inputScroll = CreateFrame("ScrollFrame", nil, window, "InputScrollFrameTemplate")
    inputScroll:SetPoint("TOPLEFT", nameText, "BOTTOMLEFT", -6, -10)
    inputScroll:SetPoint("BOTTOMRIGHT", window, "BOTTOMRIGHT", -32, 70)

    local edit = inputScroll.EditBox
    edit:SetAutoFocus(false)
    edit:SetText(tostring(shareCode or ""))
    if edit.SetTextColor then
        edit:SetTextColor(1, 1, 1, 1)
    end
    edit:HighlightText()
    edit:SetScript("OnEscapePressed", function(self) self:ClearFocus() end)

    local clickCatcher = CreateFrame("Button", nil, inputScroll)
    clickCatcher:SetAllPoints(inputScroll)
    clickCatcher:RegisterForClicks("LeftButtonDown", "RightButtonDown")
    clickCatcher:SetScript("OnMouseDown", function()
        edit:SetFocus()
        edit:HighlightText()
    end)

    local copyBtn
    local closeBtn
    if AC.CreateProfileStyleButton then
        closeBtn = AC:CreateProfileStyleButton(window, 140, 30, "Close", "danger", 12)
        closeBtn:SetPoint("BOTTOMRIGHT", -16, 14)
        closeBtn:SetScript("OnClick", function() window:Hide() end)

        copyBtn = AC:CreateProfileStyleButton(window, 140, 30, "Select All", "primary", 12)
        copyBtn:SetPoint("RIGHT", closeBtn, "LEFT", -10, 0)
    else
        closeBtn = CreateFrame("Button", nil, window, "UIPanelButtonTemplate")
        closeBtn:SetSize(140, 26)
        closeBtn:SetPoint("BOTTOMRIGHT", -16, 14)
        closeBtn:SetText("Close")
        closeBtn:SetScript("OnClick", function() window:Hide() end)

        copyBtn = CreateFrame("Button", nil, window, "UIPanelButtonTemplate")
        copyBtn:SetSize(140, 26)
        copyBtn:SetPoint("RIGHT", closeBtn, "LEFT", -10, 0)
        copyBtn:SetText("Select All")
    end

    copyBtn:SetScript("OnClick", function()
        edit:SetFocus()
        edit:HighlightText()
    end)

    window:Show()
    C_Timer.After(0, function()
        edit:SetFocus()
        edit:HighlightText()
    end)
end

local function CreateProfilesPage(container)
    if not container then return end

    if V and V.EnsureMottoStrip then
        V:EnsureMottoStrip(container)
    end

    local COLORS = AC.COLORS or {}
    local CUSTOM_FONT = "Interface\\AddOns\\ArenaCore\\Media\\Fonts\\arenacore.ttf"

    local strip = CreateFrame("Frame", nil, container)
    strip:SetHeight(44)
    if strip.SetClipsChildren then
        strip:SetClipsChildren(false)
    end

    if container._mottoStrip then
        strip:SetPoint("TOPLEFT", container._mottoStrip, "BOTTOMLEFT", 0, -8)
        strip:SetPoint("TOPRIGHT", container._mottoStrip, "BOTTOMRIGHT", 0, -8)
    else
        strip:SetPoint("TOPLEFT", 6, -52)
        strip:SetPoint("TOPRIGHT", -6, -52)
    end

    local sBorder = AC:CreateFlatTexture(strip, "BACKGROUND", 1, COLORS.BORDER_LIGHT, 0.6)
    sBorder:SetAllPoints()

    local sFill = AC:CreateFlatTexture(strip, "BACKGROUND", 2, COLORS.INPUT_DARK or {0.12, 0.12, 0.12, 1}, 1)
    sFill:SetPoint("TOPLEFT", 1, -1)
    sFill:SetPoint("BOTTOMRIGHT", -1, 1)

    local tabRow = CreateFrame("Frame", nil, strip)
    tabRow:SetHeight(30)
    tabRow:SetFrameLevel((strip:GetFrameLevel() or 1) + 2)
    if tabRow.SetClipsChildren then
        tabRow:SetClipsChildren(false)
    end
    tabRow:SetPoint("TOPLEFT", 0, -7)
    tabRow:SetPoint("TOPRIGHT", 0, -7)

    local function CreateProfilesTabButton(parent, text, width, height)
        local btn = CreateFrame("Button", nil, parent)
        btn:SetSize(width or 130, height or 30)

        local bg = AC:CreateFlatTexture(btn, "BACKGROUND", 0, {0.06, 0.06, 0.06, 1}, 1)
        bg:SetAllPoints()
        btn.bg = bg

        local hover = AC:CreateFlatTexture(btn, "ARTWORK", 1, COLORS.BORDER_LIGHT or {0.278, 0.278, 0.278, 1}, 0.15)
        hover:SetAllPoints()
        hover:Hide()
        btn.hover = hover

        local glow = btn:CreateTexture(nil, "OVERLAY")
        glow:SetTexture("Interface\\AddOns\\ArenaCore\\Media\\UI\\tab-purple-matte.tga")
        glow:SetAllPoints()
        glow:SetBlendMode("ADD")
        glow:SetAlpha(0)
        btn.glow = glow

        local function CreateGlowLine()
            local t = btn:CreateTexture(nil, "OVERLAY", nil, 7)
            local c = COLORS.PRIMARY or {0.545, 0.271, 1.000, 1}
            t:SetColorTexture(c[1], c[2], c[3], 1)
            if t.SetSnapToPixelGrid then t:SetSnapToPixelGrid(true) end
            if t.SetTexelSnappingBias then t:SetTexelSnappingBias(0) end
            t:Hide()
            return t
        end

        local outlineTop = CreateGlowLine()
        outlineTop:SetPoint("TOPLEFT", btn, "TOPLEFT", 1, -1)
        outlineTop:SetPoint("TOPRIGHT", btn, "TOPRIGHT", -1, -1)
        outlineTop:SetHeight(1)

        local outlineBottom = CreateGlowLine()
        outlineBottom:SetPoint("BOTTOMLEFT", btn, "BOTTOMLEFT", 1, 1)
        outlineBottom:SetPoint("BOTTOMRIGHT", btn, "BOTTOMRIGHT", -1, 1)
        outlineBottom:SetHeight(1)

        local outlineLeft = CreateGlowLine()
        outlineLeft:SetPoint("TOPLEFT", btn, "TOPLEFT", 1, -1)
        outlineLeft:SetPoint("BOTTOMLEFT", btn, "BOTTOMLEFT", 1, 1)
        outlineLeft:SetWidth(1)

        local outlineRight = CreateGlowLine()
        outlineRight:SetPoint("TOPRIGHT", btn, "TOPRIGHT", -1, -1)
        outlineRight:SetPoint("BOTTOMRIGHT", btn, "BOTTOMRIGHT", -1, 1)
        outlineRight:SetWidth(1)

        btn.outlineTop = outlineTop
        btn.outlineBottom = outlineBottom
        btn.outlineLeft = outlineLeft
        btn.outlineRight = outlineRight

        local label = AC:CreateStyledText(btn, text or "", 11, (COLORS.TEXT_2 or {0.706, 0.706, 0.706, 1}), "OVERLAY", "")
        label:SetPoint("CENTER", 0, 0)
        btn.label = label

        btn.isSelected = false

        function btn:SetSelected(selected)
            self.isSelected = selected and true or false

            if self.isSelected then
                self.bg:SetColorTexture(0.11, 0.11, 0.11, 1)
                self.hover:Hide()
                self.outlineTop:Show()
                self.outlineBottom:Show()
                self.outlineLeft:Show()
                self.outlineRight:Show()
                if self.glow then
                    self.glow:SetAlpha(0.22)
                end
                self.label:SetTextColor((COLORS.TEXT and COLORS.TEXT[1]) or 1, (COLORS.TEXT and COLORS.TEXT[2]) or 1, (COLORS.TEXT and COLORS.TEXT[3]) or 1, 1)
            else
                self.bg:SetColorTexture(0.06, 0.06, 0.06, 1)
                self.outlineTop:Hide()
                self.outlineBottom:Hide()
                self.outlineLeft:Hide()
                self.outlineRight:Hide()
                if self.glow then
                    self.glow:SetAlpha(0)
                end
                self.label:SetTextColor((COLORS.TEXT_2 and COLORS.TEXT_2[1]) or 0.706, (COLORS.TEXT_2 and COLORS.TEXT_2[2]) or 0.706, (COLORS.TEXT_2 and COLORS.TEXT_2[3]) or 0.706, 1)
            end
        end

        btn:SetScript("OnEnter", function(selfBtn)
            if not selfBtn.isSelected then
                selfBtn.hover:Show()
                selfBtn.outlineTop:Show()
                selfBtn.outlineBottom:Show()
                selfBtn.outlineLeft:Show()
                selfBtn.outlineRight:Show()
                if selfBtn.glow then
                    selfBtn.glow:SetAlpha(0.22)
                end
                selfBtn.label:SetTextColor((COLORS.TEXT and COLORS.TEXT[1]) or 1, (COLORS.TEXT and COLORS.TEXT[2]) or 1, (COLORS.TEXT and COLORS.TEXT[3]) or 1, 1)
            end
        end)

        btn:SetScript("OnLeave", function(selfBtn)
            if not selfBtn.isSelected then
                selfBtn.hover:Hide()
                selfBtn.outlineTop:Hide()
                selfBtn.outlineBottom:Hide()
                selfBtn.outlineLeft:Hide()
                selfBtn.outlineRight:Hide()
                if selfBtn.glow then
                    selfBtn.glow:SetAlpha(0)
                end
                selfBtn.label:SetTextColor((COLORS.TEXT_2 and COLORS.TEXT_2[1]) or 0.706, (COLORS.TEXT_2 and COLORS.TEXT_2[2]) or 0.706, (COLORS.TEXT_2 and COLORS.TEXT_2[3]) or 0.706, 1)
            end
        end)

        return btn
    end

    local tabs = {}
    local contentFrames = {}
    local activeTab = "management"

    local contentRoot = CreateFrame("Frame", nil, container)
    contentRoot:SetPoint("TOPLEFT", strip, "BOTTOMLEFT", 0, -10)
    contentRoot:SetPoint("TOPRIGHT", strip, "BOTTOMRIGHT", 0, -10)
    contentRoot:SetPoint("BOTTOMLEFT", 0, 0)
    contentRoot:SetPoint("BOTTOMRIGHT", 0, 0)

    local dropdown
    local nameInput
    local profileCount

    local function GetProfileCount()
        if not AC.ProfileManager then return "0/8" end
        local profiles = AC.ProfileManager:GetProfileList()
        return #profiles .. "/" .. (AC.ProfileManager.MAX_PROFILES or 8)
    end

    local function CreateProfileButton(parent, width, height, text, colorType)
        local btn = CreateFrame("Button", nil, parent)
        btn:SetSize(width, height)

        local colors = {
            primary = {
                bg = {0.545, 0.271, 1.000, 1},
                border = {0.4, 0.2, 0.7, 1},
                hover = {0.645, 0.371, 1.000, 1}
            },
            success = {
                bg = {0.133, 0.667, 0.267, 1},
                border = {0.1, 0.5, 0.2, 1},
                hover = {0.233, 0.767, 0.367, 1}
            },
            danger = {
                bg = {0.863, 0.176, 0.176, 1},
                border = {0.6, 0.1, 0.1, 1},
                hover = {0.963, 0.276, 0.276, 1}
            }
        }

        local color = colors[colorType] or colors.primary

        local bg = btn:CreateTexture(nil, "BACKGROUND")
        bg:SetAllPoints()
        bg:SetColorTexture(color.bg[1], color.bg[2], color.bg[3], color.bg[4])
        btn.bg = bg

        local glow = btn:CreateTexture(nil, "OVERLAY")
        glow:SetTexture("Interface\\AddOns\\ArenaCore\\Media\\UI\\tab-purple-matte.tga")
        glow:SetAllPoints()
        glow:SetBlendMode("ADD")
        glow:SetAlpha(0)
        btn.glow = glow

        local border = btn:CreateTexture(nil, "BORDER")
        border:SetAllPoints()
        border:SetColorTexture(color.border[1], color.border[2], color.border[3], color.border[4])
        border:SetPoint("TOPLEFT", 1, -1)
        border:SetPoint("BOTTOMRIGHT", -1, 1)

        local btnText = btn:CreateFontString(nil, "OVERLAY")
        btnText:SetFont("Interface/AddOns/ArenaCore/Media/Fonts/arenacore.ttf", 11)
        btnText:SetText(text)
        btnText:SetTextColor(1, 1, 1, 1)
        btnText:SetPoint("CENTER", 0, 0)
        btn.text = btnText

        btn:SetScript("OnEnter", function(self)
            self.bg:SetColorTexture(color.hover[1], color.hover[2], color.hover[3], color.hover[4])
            if self.glow then
                self.glow:SetAlpha(0.25)
            end
        end)

        btn:SetScript("OnLeave", function(self)
            self.bg:SetColorTexture(color.bg[1], color.bg[2], color.bg[3], color.bg[4])
            if self.glow then
                self.glow:SetAlpha(0)
            end
        end)

        return btn
    end

    local function RefreshDropdown(parentGroup)
        if not AC.ProfileManager then return end
        if not parentGroup then return end

        local profiles = AC.ProfileManager:GetProfileList()
        local currentProfile = AC.ProfileManager:GetCurrentProfile()
        local defaultProfile = AC.ProfileManager.DEFAULT_PROFILE_NAME or "ArenaCore Default"

        local function OnProfileChange(selectedProfile)
            local success, err = AC.ProfileManager:SwitchProfile(selectedProfile)
            if not success then
                print("|cffFF0000ArenaCore:|r " .. (err or "Failed to switch profile"))
                return
            end

            ShowReloadConfirmation(selectedProfile)
        end

        local function OnProfileDelete(profileToDelete)
            PlaySound(SOUNDKIT.IG_MAINMENU_OPTION)

            if profileToDelete == currentProfile then
                ShowActiveProfileError()
                print("|cffFF0000ArenaCore:|r Cannot delete active profile. Please switch to another profile first.")
                return
            end

            ShowDeleteConfirmation(profileToDelete, function()
                local success, err = AC.ProfileManager:DeleteProfile(profileToDelete)
                if success then
                    RefreshDropdown(parentGroup)
                    if nameInput then
                        nameInput:SetText(AC.ProfileManager:GetCurrentProfile())
                    end
                    if container.UpdateProfileCount then
                        container.UpdateProfileCount()
                    end
                else
                    print("|cffFF0000ArenaCore:|r " .. (err or "Failed to delete profile"))
                end
            end)
        end

        if dropdown then
            if dropdown.menu then
                dropdown.menu:Hide()
                dropdown.menu:SetParent(nil)
            end
            dropdown:Hide()
            dropdown:SetParent(nil)
            dropdown = nil
        end

        dropdown = AC:CreateProfileDropdown(parentGroup, 300, 30, profiles, currentProfile, OnProfileChange, OnProfileDelete, defaultProfile, currentProfile)
        dropdown:SetPoint("TOPLEFT", 20, -70)

        container.profileDropdown = dropdown
    end

    local function BuildManagement(parent)
        local settingsGroup = CreateFrame("Frame", nil, parent)
        settingsGroup:SetPoint("TOPLEFT", 12, -12)
        settingsGroup:SetPoint("TOPRIGHT", -12, -12)
        settingsGroup:SetHeight(260)
        if AC.HairlineGroupBox then
            AC:HairlineGroupBox(settingsGroup)
        else
            ApplyAtlasCardBg(settingsGroup)
        end

        local groupTitle = AC:CreateStyledText(settingsGroup, "PROFILE MANAGEMENT", 13, COLORS.PRIMARY, "OVERLAY", CUSTOM_FONT)
        groupTitle:SetPoint("TOPLEFT", 15, -18)

        local yOffset = -45

        local dropdownLabel = AC:CreateStyledText(settingsGroup, "Current Profile:", 12, COLORS.TEXT_2, "OVERLAY", CUSTOM_FONT)
        dropdownLabel:SetPoint("TOPLEFT", 20, yOffset)

        RefreshDropdown(settingsGroup)

        yOffset = yOffset - 100

        local nameLabel = AC:CreateStyledText(settingsGroup, "Profile Name:", 12, COLORS.TEXT_2, "OVERLAY", CUSTOM_FONT)
        nameLabel:SetPoint("TOPLEFT", 20, yOffset)

        nameInput = CreateFrame("EditBox", nil, settingsGroup)
        nameInput:SetPoint("TOPLEFT", 20, yOffset - 25)
        nameInput:SetSize(300, 30)
        nameInput:SetAutoFocus(false)
        nameInput:SetFontObject(GameFontNormal)
        nameInput:SetTextColor(0.2, 0.8, 0.2, 1)
        nameInput:SetMaxLetters(50)

        local inputBg = AC:CreateFlatTexture(nameInput, "BACKGROUND", 1, COLORS.INPUT_DARK, 1)
        inputBg:SetAllPoints()

        local inputBorder = AC:CreateFlatTexture(nameInput, "BORDER", 1, COLORS.BORDER, 1)
        inputBorder:SetAllPoints()

        nameInput:SetText(AC.ProfileManager and AC.ProfileManager:GetCurrentProfile() or "")
        nameInput:SetCursorPosition(0)

        yOffset = yOffset - 60

        local renameBtn = CreateProfileButton(settingsGroup, 145, 32, "Rename Profile", "primary")
        renameBtn:SetPoint("TOPLEFT", 20, yOffset)
        renameBtn:SetScript("OnClick", function()
            if not AC.ProfileManager then return end

            local newName = nameInput:GetText()
            local currentProfile = AC.ProfileManager:GetCurrentProfile()

            if not newName or newName == "" then
                print("|cffFF0000ArenaCore:|r Profile name cannot be empty")
                return
            end

            local success, err = AC.ProfileManager:RenameProfile(currentProfile, newName)
            if success then
                nameInput:SetText(newName)
                RefreshDropdown(settingsGroup)
            else
                print("|cffFF0000ArenaCore:|r " .. (err or "Failed to rename profile"))
            end
        end)

        local createBtn = CreateProfileButton(settingsGroup, 145, 32, "Create New Profile", "primary")
        createBtn:SetPoint("TOPLEFT", 175, yOffset)
        createBtn:SetScript("OnClick", function()
            if not AC.ProfileManager then return end

            local newName = nameInput:GetText()

            if not newName or newName == "" then
                print("|cffFF0000ArenaCore:|r Please enter a profile name")
                return
            end

            local success, err = AC.ProfileManager:CreateProfile(newName)
            if success then
                RefreshDropdown(settingsGroup)
                nameInput:SetText(newName)

                if container.UpdateProfileCount then
                    container.UpdateProfileCount()
                end
            else
                print("|cffFF0000ArenaCore:|r " .. tostring(err))
            end
        end)

        yOffset = yOffset - 40

        local saveBtn = CreateProfileButton(settingsGroup, 300, 32, "Save to Current Profile", "success")
        saveBtn:SetPoint("TOPLEFT", 20, yOffset)
        saveBtn:SetScript("OnClick", function()
            if not AC.ProfileManager then return end

            local currentProfile = AC.ProfileManager:GetCurrentProfile()
            local success, err = AC.ProfileManager:SaveCurrentToProfile(currentProfile)
            if success then
                print("|cff8B45FFArenaCore:|r Profile saved successfully!")
            else
                print("|cffFF0000ArenaCore:|r " .. (err or "Failed to save profile"))
            end
        end)

        yOffset = yOffset - 50

        profileCount = AC:CreateStyledText(settingsGroup, "Profiles: " .. GetProfileCount(), 11, COLORS.TEXT_MUTED, "OVERLAY", CUSTOM_FONT)
        profileCount:SetPoint("TOPLEFT", 20, yOffset)

        C_Timer.After(0, function()
            if not settingsGroup or not settingsGroup.SetHeight then return end
            if not profileCount then return end

            local textHeight = 12
            if profileCount.GetStringHeight then
                textHeight = profileCount:GetStringHeight() or textHeight
            end

            local padding = 26
            local newHeight = math.abs(yOffset) + textHeight + padding
            settingsGroup:SetHeight(newHeight)
        end)

        container.RefreshDropdown = function()
            RefreshDropdown(settingsGroup)
        end
        container.UpdateProfileCount = function()
            if profileCount then
                profileCount:SetText("Profiles: " .. GetProfileCount())
            end
        end

        AC._profilesPageContainer = container
    end

    local function BuildSharing(parent)
        local settingsGroup = CreateFrame("Frame", nil, parent)
        settingsGroup:SetPoint("TOPLEFT", 12, -12)
        settingsGroup:SetPoint("TOPRIGHT", -12, -12)
        settingsGroup:SetHeight(220)
        if AC.HairlineGroupBox then
            AC:HairlineGroupBox(settingsGroup)
        else
            ApplyAtlasCardBg(settingsGroup)
        end

        local groupTitle = AC:CreateStyledText(settingsGroup, "PROFILE SHARING", 13, COLORS.PRIMARY, "OVERLAY", CUSTOM_FONT)
        groupTitle:SetPoint("TOPLEFT", 15, -18)

        local shareBtn = CreateProfileButton(settingsGroup, 145, 32, "Share Profile", "primary")
        shareBtn:SetPoint("TOPLEFT", 20, -55)
        shareBtn:SetScript("OnClick", function()
            if not AC.ProfileManager then return end

            local currentProfile = AC.ProfileManager:GetCurrentProfile()

            local shareCode, err = AC.ProfileManager:ExportProfile(currentProfile)
            if not shareCode then
                print("|cffFF0000ArenaCore:|r Failed to export profile: " .. tostring(err))
                return
            end

            ShowShareProfileWindow(shareCode, currentProfile)
        end)

        local importBtn = CreateProfileButton(settingsGroup, 145, 32, "Import Profile", "primary")
        importBtn:SetPoint("TOPLEFT", 175, -55)
        importBtn:SetScript("OnClick", function()
            ShowImportWindow(function()
                if container.RefreshDropdown then
                    container.RefreshDropdown()
                end
                if container.UpdateProfileCount then
                    container.UpdateProfileCount()
                end
            end)
        end)
    end

    local function ShowPresetLoadConfirmation(presetEntry)
        local popup = CreateModalBase("ArenaCorePresetLoadPopup", 440, 200)

        local title = popup:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        title:SetPoint("TOP", 0, -16)
        title:SetText("Load Preset Layout")

        local msg = popup:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        msg:SetPoint("TOP", title, "BOTTOM", 0, -10)
        msg:SetWidth(400)
        msg:SetJustifyH("CENTER")
        msg:SetText(
            "This will create a new profile called |cff8B45FF" .. presetEntry.profileName .. "|r\n" ..
            "with " .. presetEntry.name .. "'s exact settings.\n\n" ..
            "Your current profile will not be changed."
        )

        local loadBtn
        local cancelBtn

        if AC.CreateProfileStyleButton then
            loadBtn = AC:CreateProfileStyleButton(popup, 140, 30, "Load", "primary", 12)
            loadBtn:SetPoint("BOTTOM", -80, 14)

            cancelBtn = AC:CreateProfileStyleButton(popup, 140, 30, "Cancel", "danger", 12)
            cancelBtn:SetPoint("BOTTOM", 80, 14)
        else
            loadBtn = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
            loadBtn:SetSize(140, 26)
            loadBtn:SetPoint("BOTTOM", -80, 14)
            loadBtn:SetText("Load")

            cancelBtn = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
            cancelBtn:SetSize(140, 26)
            cancelBtn:SetPoint("BOTTOM", 80, 14)
            cancelBtn:SetText("Cancel")
        end

        cancelBtn:SetScript("OnClick", function() popup:Hide() end)

        loadBtn:SetScript("OnClick", function()
            popup:Hide()

            if not AC.ProfileManager then
                print("|cffFF0000ArenaCore:|r Profile system not available")
                return
            end

            -- Pass forceTheme to ImportProfile for one-time theme switching
            local success, err = AC.ProfileManager:ImportProfile(
                presetEntry.shareCode, 
                presetEntry.profileName,
                presetEntry.profileName == "Venruki" and "Just Blastin'" or nil
            )
            if not success then
                print("|cffFF0000ArenaCore:|r " .. tostring(err or "Failed to load preset"))
                return
            end

            ShowReloadConfirmation(presetEntry.profileName)
        end)

        popup:Show()
    end

    local function CreatePresetCard(parent, presetEntry, yOffset)
        local card = CreateFrame("Frame", nil, parent)
        card:SetPoint("TOPLEFT", 12, yOffset)
        card:SetPoint("TOPRIGHT", -12, yOffset)
        
        -- Venruki card needs more height for its long description
        local cardHeight = (presetEntry.profileName == "Venruki") and 194 or 164
        card:SetHeight(cardHeight)

        if AC.HairlineGroupBox then
            AC:HairlineGroupBox(card)
        else
            ApplyAtlasCardBg(card)
        end

        --- player name, big and bold
        local nameText = card:CreateFontString(nil, "OVERLAY")
        nameText:SetFont(CUSTOM_FONT, 14)
        nameText:SetPoint("TOPLEFT", 16, -14)
        nameText:SetText("|cffffffff" .. presetEntry.name .. "|r")

        --- toast line - the vanity descriptor
        local toastText = card:CreateFontString(nil, "OVERLAY")
        toastText:SetFont(CUSTOM_FONT, 11)
        toastText:SetPoint("TOPLEFT", nameText, "BOTTOMLEFT", 0, -4)
        toastText:SetText("|cff8B45FF" .. presetEntry.toast .. "|r")

        --- description line
        local descText = card:CreateFontString(nil, "OVERLAY")
        descText:SetFont(CUSTOM_FONT, 10)
        descText:SetPoint("TOPLEFT", toastText, "BOTTOMLEFT", 0, -4)
        descText:SetPoint("RIGHT", card, "RIGHT", -160, 0)
        descText:SetPoint("BOTTOM", card, "BOTTOM", 0, 18)
        descText:SetText("|cffb4b4b4" .. presetEntry.description .. "|r")
        descText:SetJustifyH("LEFT")
        descText:SetWordWrap(true)

        --- load button on the right side
        local buttonText = presetEntry.comingSoon and "Coming Soon.." or "Load Profile"
        local loadBtn = CreateProfileButton(card, 120, 30, buttonText, "primary")
        loadBtn:SetPoint("RIGHT", card, "RIGHT", -16, 0)
        
        if presetEntry.comingSoon then
            -- Disable button for coming soon profiles
            loadBtn:Disable()
            if loadBtn.text then
                loadBtn.text:SetTextColor(0.5, 0.5, 0.5, 1)
            end
        else
            loadBtn:SetScript("OnClick", function()
                ShowPresetLoadConfirmation(presetEntry)
            end)
        end

        return card
    end

    local function BuildCustomLayouts(parent)
        --- intro header group
        local introGroup = CreateFrame("Frame", nil, parent)
        introGroup:SetPoint("TOPLEFT", 12, -12)
        introGroup:SetPoint("TOPRIGHT", -12, -12)
        introGroup:SetHeight(134)
        if AC.HairlineGroupBox then
            AC:HairlineGroupBox(introGroup)
        else
            ApplyAtlasCardBg(introGroup)
        end

        local groupTitle = AC:CreateStyledText(introGroup, "CUSTOM LAYOUTS", 13, COLORS.PRIMARY, "OVERLAY", CUSTOM_FONT)
        groupTitle:SetPoint("TOPLEFT", 15, -18)

        local introText = AC:CreateStyledText(introGroup,
            "|cffffffffCustom layouts of some of the best players in the world.|r\n" ..
            "|cffb4b4b4Directly download and use exact settings and theme layouts from various players that use Arena Core and have put the time and effort into perfecting their settings in detail.|r\n\n" ..
            "|cff8B45FFDon\"t play the guessing game.|r |cffffffffJump right into the minds of the top players on the planet.|r",
            11, COLORS.TEXT_2, "OVERLAY", CUSTOM_FONT)
        introText:SetPoint("TOPLEFT", 16, -42)
        introText:SetPoint("TOPRIGHT", -16, -42)
        introText:SetPoint("BOTTOM", introGroup, "BOTTOM", 0, 14)
        introText:SetJustifyH("LEFT")

        --- build cards from preset data
        local presets = AC.PresetLayouts or {}
        local cardY = -154

        for i, entry in ipairs(presets) do
            CreatePresetCard(parent, entry, cardY)
            -- Adjust spacing based on card height (Venruki is taller)
            local cardHeight = (entry.profileName == "Venruki") and 194 or 164
            cardY = cardY - (cardHeight + 12) -- 12px gap between cards
        end

        --- more to come teaser
        local moreText = parent:CreateFontString(nil, "OVERLAY")
        moreText:SetFont(CUSTOM_FONT, 11)
        moreText:SetPoint("TOPLEFT", 24, cardY - 8)
        moreText:SetText("|cff666666More player layouts coming soon...|r")
    end

    local function EnsureContentFrame(id)
        if contentFrames[id] then return contentFrames[id] end
        local f = CreateFrame("Frame", nil, contentRoot)
        f:SetAllPoints()
        f:Hide()
        contentFrames[id] = f

        if id == "management" then
            BuildManagement(f)
        elseif id == "sharing" then
            BuildSharing(f)
        elseif id == "customLayouts" then
            BuildCustomLayouts(f)
        end

        return f
    end

    local function SetActiveTab(id)
        activeTab = id
        for _, b in ipairs(tabs) do
            b:SetSelected(b._tabId == id)
        end
        for pid, f in pairs(contentFrames) do
            if pid == id then
                f:Show()
            else
                f:Hide()
            end
        end
        if AC.UpdateContentHeight then
            C_Timer.After(0.05, function()
                AC:UpdateContentHeight()
            end)
        end
    end

    local btnManagement = CreateProfilesTabButton(tabRow, "Management", 110, 30)
    btnManagement._tabId = "management"
    btnManagement:SetPoint("TOPLEFT", 18, 0)
    table.insert(tabs, btnManagement)
    btnManagement:SetScript("OnClick", function()
        EnsureContentFrame("management")
        SetActiveTab("management")
    end)

    local btnSharing = CreateProfilesTabButton(tabRow, "Sharing", 110, 30)
    btnSharing._tabId = "sharing"
    btnSharing:SetPoint("LEFT", btnManagement, "RIGHT", 8, 0)
    table.insert(tabs, btnSharing)
    btnSharing:SetScript("OnClick", function()
        EnsureContentFrame("sharing")
        SetActiveTab("sharing")
    end)

    local btnCustomLayouts = CreateProfilesTabButton(tabRow, "Custom Layouts", 130, 30)
    btnCustomLayouts._tabId = "customLayouts"
    btnCustomLayouts:SetPoint("LEFT", btnSharing, "RIGHT", 8, 0)
    table.insert(tabs, btnCustomLayouts)
    btnCustomLayouts:SetScript("OnClick", function()
        EnsureContentFrame("customLayouts")
        SetActiveTab("customLayouts")
    end)

    EnsureContentFrame("management")
    EnsureContentFrame("sharing")
    EnsureContentFrame("customLayouts")
    SetActiveTab("management")
end

AC:RegisterPage("Profiles", CreateProfilesPage)
