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

local V = AC.Vanity
local L = AC.UILocalization

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(L and L:Get("PROFILES", "cannot_delete_active") or "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(L and L:Get("PROFILES", "switch_first") or "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(L and L:Get("PROFILES", "cancel") or "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(L and L:Get("PROFILES", "reload_required") or "Reload Required")

    local msg = popup:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    msg:SetPoint("TOP", title, "BOTTOM", 0, -12)
    msg:SetWidth(380)
    msg:SetJustifyH("CENTER")
    msg:SetText(string.format(L and L:Get("PROFILES", "profile_switched") or "Profile switched to '%s'.\nReload your UI to fully apply it.", tostring(profileName)))

    local reloadBtn = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
    reloadBtn:SetSize(140, 26)
    reloadBtn:SetPoint("BOTTOM", -75, 14)
    reloadBtn:SetText(L and L:Get("PROFILES", "reload") or "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(L and L:Get("PROFILES", "later") or "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(L and L:Get("PROFILES", "delete_profile") or "Delete Profile?")

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

    local deleteBtn = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
    deleteBtn:SetSize(140, 26)
    deleteBtn:SetPoint("BOTTOM", -75, 14)
    deleteBtn:SetText(L and L:Get("PROFILES", "delete") or "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(L and L:Get("PROFILES", "cancel") or "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(L and L:Get("PROFILES", "import_profile") or "Import Profile")
    title:SetTextColor(1, 1, 1, 1)

    local nameLabel = window:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    nameLabel:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -12)
    nameLabel:SetText(L and L:Get("PROFILES", "profile_name") or "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(L and L:Get("PROFILES", "paste_import") or "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, L and L:Get("PROFILES", "import") or "Import", "primary", 12)
        importBtn:SetPoint("BOTTOMRIGHT", -16, 14)

        closeBtn = AC:CreateProfileStyleButton(window, 140, 30, L and L:Get("PROFILES", "close") or "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(L and L:Get("PROFILES", "import") or "Import")

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

    importBtn:SetScript("OnClick", function()
        if not AC.ProfileManager then
            statusText:SetText("|cffFF0000" .. (L and L:Get("PROFILES", "profile_unavailable") or "Profile 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 (L and L:Get("PROFILES", "import_failed") or "Import failed")) .. "|r")
            return
        end

        statusText:SetText("|cff00FF00" .. (L and L:Get("PROFILES", "imported_activated") or "Imported 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 ShowPreviewWindow(imagePath, playerName)
    local window = CreateModalBase("ArenaCorePreviewWindow", 740, 480)
    window:SetBackdropColor(0.04, 0.04, 0.04, 0.95)

    local title = window:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOP", 0, -14)
    title:SetText("|cffffffff" .. (playerName or "Layout Preview") .. "|r")
    title:SetTextColor(1, 1, 1, 1)

    local subtitle = window:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    subtitle:SetPoint("TOP", title, "BOTTOM", 0, -4)
    subtitle:SetText("|cff8B45FFArenaCore Layout Preview|r")
    subtitle:SetTextColor(0.545, 0.271, 1, 1)

    -- image container with dark backing
    local imgContainer = CreateFrame("Frame", nil, window, "BackdropTemplate")
    imgContainer:SetPoint("TOPLEFT", subtitle, "BOTTOMLEFT", -80, -12)
    imgContainer:SetPoint("BOTTOMRIGHT", window, "BOTTOMRIGHT", -16, 56)
    imgContainer:SetBackdrop({
        bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        edgeSize = 12,
        insets = { left = 2, right = 2, top = 2, bottom = 2 }
    })
    imgContainer:SetBackdropColor(0.06, 0.06, 0.06, 1)
    imgContainer:SetBackdropBorderColor(0.2, 0.2, 0.2, 1)

    local previewImg = imgContainer:CreateTexture(nil, "ARTWORK")
    previewImg:SetTexture(imagePath)
    previewImg:SetPoint("TOPLEFT", imgContainer, "TOPLEFT", 4, -4)
    previewImg:SetPoint("BOTTOMRIGHT", imgContainer, "BOTTOMRIGHT", -4, 4)

    local closeBtn
    if AC.CreateProfileStyleButton then
        closeBtn = AC:CreateProfileStyleButton(window, 140, 30, "Close", "danger", 12)
        closeBtn:SetPoint("BOTTOM", 0, 14)
    else
        closeBtn = CreateFrame("Button", nil, window, "UIPanelButtonTemplate")
        closeBtn:SetSize(140, 26)
        closeBtn:SetPoint("BOTTOM", 0, 14)
        closeBtn:SetText("Close")
    end
    closeBtn:SetScript("OnClick", function() window:Hide() end)

    -- ESC to close
    window:SetScript("OnKeyDown", function(self, key)
        if key == "ESCAPE" then
            self:Hide()
            self:SetPropagateKeyboardInput(false)
        else
            self:SetPropagateKeyboardInput(true)
        end
    end)
    window:EnableKeyboard(true)

    window:Show()
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(L and L:Get("PROFILES", "share_profile") or "Share Profile")
    title:SetTextColor(1, 1, 1, 1)

    local sub = window:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    sub:SetPoint("TOPLEFT", title, "BOTTOMLEFT", 0, -6)
    sub:SetText(L and L:Get("PROFILES", "share_description") or "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(string.format(L and L:Get("PROFILES", "profile_label") or "Profile: %s", 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, L and L:Get("PROFILES", "close") or "Close", "danger", 12)
        closeBtn:SetPoint("BOTTOMRIGHT", -16, 14)
        closeBtn:SetScript("OnClick", function() window:Hide() end)

        copyBtn = AC:CreateProfileStyleButton(window, 140, 30, L and L:Get("PROFILES", "select_all") or "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(L and L:Get("PROFILES", "close") or "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(L and L:Get("PROFILES", "select_all") or "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/20" end
        local profiles = AC.ProfileManager:GetProfileList()
        return #profiles .. "/" .. (AC.ProfileManager.MAX_PROFILES or 20)
    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)

        -- CRITICAL FIX: Use locale-appropriate font for CJK support
        local currentLocale = GetLocale()
        local usesCJK = (currentLocale == "zhCN" or currentLocale == "zhTW" or 
                        currentLocale == "koKR" or currentLocale == "ruRU")
        local buttonFont = usesCJK and GameFontNormal:GetFont() or "Interface\\AddOns\\ArenaCore\\Media\\Fonts\\arenacore.ttf"

        local btnText = btn:CreateFontString(nil, "OVERLAY")
        btnText:SetFont(buttonFont, 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 (L and L:Get("PROFILES", "failed_switch") 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 " .. (L and L:Get("PROFILES", "cannot_delete_active_msg") or "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 (L and L:Get("PROFILES", "failed_delete") 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, L and L:Get("PROFILES", "management") or "PROFILE MANAGEMENT", 13, COLORS.PRIMARY, "OVERLAY", CUSTOM_FONT)
        groupTitle:SetPoint("TOPLEFT", 15, -18)

        local yOffset = -45

        local dropdownLabel = AC:CreateStyledText(settingsGroup, L and L:Get("PROFILES", "current_profile") or "Current Profile:", 12, COLORS.TEXT_2, "OVERLAY", CUSTOM_FONT)
        dropdownLabel:SetPoint("TOPLEFT", 20, yOffset)

        RefreshDropdown(settingsGroup)

        yOffset = yOffset - 100

        local nameLabel = AC:CreateStyledText(settingsGroup, L and L:Get("PROFILES", "profile_name") or "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, L and L:Get("PROFILES", "rename_profile") or "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 " .. (L and L:Get("PROFILES", "profile_name_empty") or "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 (L and L:Get("PROFILES", "failed_rename") or "Failed to rename profile")))
            end
        end)

        local createBtn = CreateProfileButton(settingsGroup, 145, 32, L and L:Get("PROFILES", "create_new") or "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 " .. (L and L:Get("PROFILES", "enter_profile_name") or "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, L and L:Get("PROFILES", "save_current") or "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 " .. (L and L:Get("PROFILES", "profile_saved") or "Profile saved successfully!"))
            else
                print("|cffFF0000ArenaCore:|r " .. (err or (L and L:Get("PROFILES", "failed_save") or "Failed to save profile")))
            end
        end)

        yOffset = yOffset - 50

        profileCount = AC:CreateStyledText(settingsGroup, string.format(L and L:Get("PROFILES", "profiles_count") or "Profiles: %s", 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(string.format(L and L:Get("PROFILES", "profiles_count") or "Profiles: %s", 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, L and L:Get("PROFILES", "sharing") or "PROFILE SHARING", 13, COLORS.PRIMARY, "OVERLAY", CUSTOM_FONT)
        groupTitle:SetPoint("TOPLEFT", 15, -18)

        local shareBtn = CreateProfileButton(settingsGroup, 145, 32, L and L:Get("PROFILES", "share_profile") or "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 " .. (L and L:Get("PROFILES", "failed_export") or "Failed to export profile") .. ": " .. tostring(err))
                return
            end

            ShowShareProfileWindow(shareCode, currentProfile)
        end)

        local importBtn = CreateProfileButton(settingsGroup, 145, 32, L and L:Get("PROFILES", "import_profile") or "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(L and L:Get("PROFILES", "load_preset") or "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(string.format(L and L:Get("PROFILES", "load_preset_desc") or "This will create a new profile called |cff8B45FF%s|r\nwith %s's exact settings.\n\nYour current profile will not be changed.", presetEntry.profileName, presetEntry.name))

        local loadBtn
        local cancelBtn

        if AC.CreateProfileStyleButton then
            loadBtn = AC:CreateProfileStyleButton(popup, 140, 30, L and L:Get("PROFILES", "load") or "Load", "primary", 12)
            loadBtn:SetPoint("BOTTOM", -80, 14)

            cancelBtn = AC:CreateProfileStyleButton(popup, 140, 30, L and L:Get("PROFILES", "cancel") or "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(L and L:Get("PROFILES", "load") or "Load")

            cancelBtn = CreateFrame("Button", nil, popup, "UIPanelButtonTemplate")
            cancelBtn:SetSize(140, 26)
            cancelBtn:SetPoint("BOTTOM", 80, 14)
            cancelBtn:SetText(L and L:Get("PROFILES", "cancel") or "Cancel")
        end

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

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

            if not AC.ProfileManager then
                print("|cffFF0000ArenaCore:|r " .. (L and L:Get("PROFILES", "profile_unavailable") or "Profile system not available"))
                return
            end

            -- Pass forceTheme to ImportProfile for one-time theme switching
            -- Only force theme for Venruki (special case), let other presets use their embedded theme
            local forceTheme = nil
            if presetEntry.profileName == "Venruki" then
                forceTheme = "Just Blastin'"
            end

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

            -- Wait for profile switch to complete before showing reload confirmation
            -- (ImportProfile schedules SwitchProfile with 0.5s delay for preset profiles)
            C_Timer.After(0.6, function()
                ShowReloadConfirmation(presetEntry.profileName)
            end)
        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)
        
        --- 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 or preview image
        local imgHeight = 0
        if presetEntry.previewImage then
            -- Calculate image height based on card width minus button area (148px) and margins
            local cardWidth = parent:GetWidth() or 500
            local availableWidth = cardWidth - 24 - 148 - 8 -- card margins, button area, preview padding
            imgHeight = availableWidth * 9 / 16 -- 16:9 aspect ratio
        end
        
        -- Calculate card height based on content
        local baseHeight = 164
        local nameHeight = 14 + 4 + 11 + 8 -- name + spacing + toast + spacing
        local previewHeight = imgHeight + 8 + 18 -- image + top padding (8) + bottom padding (18)
        local cardHeight = (presetEntry.previewImage) and (nameHeight + previewHeight) or baseHeight
        
        card:SetHeight(cardHeight)

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

        if presetEntry.previewImage then
            local previewBg = card:CreateTexture(nil, "BACKGROUND", nil, 1)
            previewBg:SetColorTexture(0.08, 0.08, 0.08, 1)
            previewBg:SetPoint("TOPLEFT", toastText, "BOTTOMLEFT", -4, -8)
            previewBg:SetPoint("BOTTOMRIGHT", card, "BOTTOMRIGHT", -148, 18)

            local previewImg = card:CreateTexture(nil, "ARTWORK", nil, 2)
            previewImg:SetTexture(presetEntry.previewImage)
            -- CRITICAL FIX: Maintain aspect ratio to prevent vertical squishing
            -- SetTexCoord ensures full image is shown without distortion
            previewImg:SetTexCoord(0, 1, 0, 1)
            -- Anchor to TOPLEFT and set explicit size to maintain 16:9 aspect ratio
            previewImg:SetPoint("TOPLEFT", previewBg, "TOPLEFT", 2, -2)
            -- Calculate dimensions based on container width to maintain 16:9 ratio
            local bgWidth = (previewBg:GetWidth() or 400) - 4
            previewImg:SetSize(bgWidth, imgHeight)

            -- subtle border around the preview for that clean look
            local function AddPreviewBorder(target, r, g, b, a)
                local top = card:CreateTexture(nil, "OVERLAY", nil, 3)
                top:SetColorTexture(r, g, b, a)
                top:SetPoint("TOPLEFT", target, "TOPLEFT", 0, 0)
                top:SetPoint("TOPRIGHT", target, "TOPRIGHT", 0, 0)
                top:SetHeight(1)
                local bottom = card:CreateTexture(nil, "OVERLAY", nil, 3)
                bottom:SetColorTexture(r, g, b, a)
                -- CRITICAL FIX: Anchor bottom border to image bottom instead of previewBg bottom
                bottom:SetPoint("BOTTOMLEFT", previewImg, "BOTTOMLEFT", 0, 0)
                bottom:SetPoint("BOTTOMRIGHT", previewImg, "BOTTOMRIGHT", 0, 0)
                bottom:SetHeight(1)
                local left = card:CreateTexture(nil, "OVERLAY", nil, 3)
                left:SetColorTexture(r, g, b, a)
                left:SetPoint("TOPLEFT", target, "TOPLEFT", 0, 0)
                left:SetPoint("BOTTOMLEFT", target, "BOTTOMLEFT", 0, 0)
                left:SetWidth(1)
                local right = card:CreateTexture(nil, "OVERLAY", nil, 3)
                right:SetColorTexture(r, g, b, a)
                right:SetPoint("TOPRIGHT", target, "TOPRIGHT", 0, 0)
                right:SetPoint("BOTTOMRIGHT", target, "BOTTOMRIGHT", 0, 0)
                right:SetWidth(1)
            end
            AddPreviewBorder(previewBg, 0.30, 0.30, 0.30, 0.8)
        else
            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)
        end

        --- load button on the right side
        local buttonText = presetEntry.comingSoon and (L and L:Get("PROFILES", "coming_soon") or "Coming Soon..") or (L and L:Get("PROFILES", "load_profile") 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

        -- Enlarge Preview button (only for cards with a preview image)
        if presetEntry.previewImage then
            local enlargeBtn = CreateProfileButton(card, 120, 24, "Enlarge Preview", "primary")
            enlargeBtn:SetPoint("TOP", loadBtn, "BOTTOM", 0, -6)
            -- lighter / more subtle look for a secondary action
            if enlargeBtn.bg then
                enlargeBtn.bg:SetColorTexture(0.10, 0.10, 0.10, 1)
            end
            if enlargeBtn.text then
                enlargeBtn.text:SetFont(CUSTOM_FONT, 10)
                enlargeBtn.text:SetText("Enlarge Preview")
            end
            -- Override OnEnter to show glow while maintaining subtle background
            enlargeBtn:SetScript("OnEnter", function(self)
                if self.bg then self.bg:SetColorTexture(0.15, 0.15, 0.15, 1) end
                if self.glow then self.glow:SetAlpha(0.25) end
            end)
            -- Override OnLeave to hide glow while maintaining subtle background
            enlargeBtn:SetScript("OnLeave", function(self)
                if self.bg then self.bg:SetColorTexture(0.10, 0.10, 0.10, 1) end
                if self.glow then self.glow:SetAlpha(0) end
            end)
            enlargeBtn:SetScript("OnClick", function()
                ShowPreviewWindow(presetEntry.previewImage, presetEntry.name)
            end)
        end

        -- Return card height for spacing calculations
        return cardHeight
    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(164)
        if AC.HairlineGroupBox then
            AC:HairlineGroupBox(introGroup)
        else
            ApplyAtlasCardBg(introGroup)
        end

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

        local introText = AC:CreateStyledText(introGroup,
            L and L:Get("PROFILES", "custom_layouts_desc") or "|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 = -184

        for i, entry in ipairs(presets) do
            local cardHeight = CreatePresetCard(parent, entry, cardY)
            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("|cff666666" .. (L and L:Get("PROFILES", "more_coming") or "More 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, L and L:Get("PROFILES", "management_tab") or "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, L and L:Get("PROFILES", "sharing_tab") or "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, L and L:Get("PROFILES", "custom_layouts_tab") or "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)
