-- ============================================================================
-- Main Frame UI
-- ============================================================================
AIOS_CopyBox_MainFrame = {
    frame = nil,
    editBox = nil,
    scrollFrame = nil,
    isExpanded = false,
    openCloseText = nil,
    channelText = nil,
    themeText = nil,
    themeFrame = nil,
    channelFrame = nil,
    background = nil,
    glossTexture = nil,
    settingsPanel = nil
}

function AIOS_CopyBox_MainFrame:Initialize()
    if self.frame then return end

    self:CreateMainFrame()
    self:CreateHeader()
    self:CreateScrollFrame()
    self:CreateFooter()
    self:CreateSettingsPanel()

    self:RestorePosition()
    self:RestoreFontSize()
    self:RestoreMaxLines()

    if AIOS_CopyBox_ThemeManager then
        AIOS_CopyBox_ThemeManager:ApplyCurrentTheme()
    end

    if AIOS_CopyBox_Logger then
        AIOS_CopyBox_Logger:Debug("Main frame initialized", "UI")
    end
end

function AIOS_CopyBox_MainFrame:CreateMainFrame()
    local frameConfig = AIOS_CopyBox_Config:GetFrameConfig()
    local isClassic = WOW_PROJECT_ID == WOW_PROJECT_CLASSIC

    self.frame = CreateFrame("Frame", "AIOS_CopyBox_Main", UIParent)
    self.frame:SetSize(frameConfig.width, frameConfig.originalHeight)
    self.frame:SetPoint(frameConfig.position)

    self.frame:EnableMouse(true)
    self.frame:SetMovable(true)
    self.frame:RegisterForDrag("LeftButton")
    self.frame:SetScript("OnDragStart", function(self) self:StartMoving() end)
    self.frame:SetScript("OnDragStop", function(self)
        self:StopMovingOrSizing()
        AIOS_CopyBox_MainFrame:SavePosition()
        if AIOS_CopyBox_ThemeManager then
            AIOS_CopyBox_ThemeManager:ApplyCurrentTheme()
        end
    end)
    self.frame:SetFrameStrata("DIALOG")

    self.background = self.frame:CreateTexture(nil, "BACKGROUND")
    self.background:SetColorTexture(0.1, 0.1, 0.2, 0.9)

    self.glossTexture = self.frame:CreateTexture(nil, "BACKGROUND", nil, 1)
    self.glossTexture:SetTexture("Interface\\Buttons\\WHITE8x8")
    self.glossTexture:SetBlendMode("ADD")
    self.glossTexture:SetVertexColor(0.8, 0.9, 1.0, 0.15)

    if not isClassic then
        self.borderFrame = CreateFrame("Frame", nil, self.frame, "BackdropTemplate")
        self.borderFrame:SetAllPoints(self.frame)
        self.borderFrame:SetBackdrop({
            edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
            edgeSize = 16,
        })
        self.borderFrame:SetBackdropBorderColor(0.4, 0.6, 0.8, 0.8)
        self.borderFrame:SetFrameLevel(self.frame:GetFrameLevel() + 1)
    else
        self:CreateClassicBorder()
    end

    self.frame:Hide()
end

function AIOS_CopyBox_MainFrame:CreateClassicBorder()
    local borderSize = 2

    self.borderFrame = CreateFrame("Frame", nil, self.frame)
    self.borderFrame:SetPoint("TOPLEFT", -borderSize, borderSize)
    self.borderFrame:SetPoint("BOTTOMRIGHT", borderSize, -borderSize)
    self.borderFrame:SetFrameLevel(self.frame:GetFrameLevel() + 1)

    local top = self.borderFrame:CreateTexture(nil, "BORDER")
    top:SetColorTexture(0.4, 0.6, 0.8, 0.8)
    top:SetHeight(borderSize)
    top:SetPoint("TOPLEFT")
    top:SetPoint("TOPRIGHT")

    local bottom = self.borderFrame:CreateTexture(nil, "BORDER")
    bottom:SetColorTexture(0.4, 0.6, 0.8, 0.8)
    bottom:SetHeight(borderSize)
    bottom:SetPoint("BOTTOMLEFT")
    bottom:SetPoint("BOTTOMRIGHT")

    local left = self.borderFrame:CreateTexture(nil, "BORDER")
    left:SetColorTexture(0.4, 0.6, 0.8, 0.8)
    left:SetWidth(borderSize)
    left:SetPoint("TOPLEFT")
    left:SetPoint("BOTTOMLEFT")

    local right = self.borderFrame:CreateTexture(nil, "BORDER")
    right:SetColorTexture(0.4, 0.6, 0.8, 0.8)
    right:SetWidth(borderSize)
    right:SetPoint("TOPRIGHT")
    right:SetPoint("BOTTOMRIGHT")

    self.borderTextures = { top, bottom, left, right }
end

function AIOS_CopyBox_MainFrame:CreateHeader()
    local uiConfig = AIOS_CopyBox_Config:GetUIConfig()

    local logo = self.frame:CreateTexture(nil, "ARTWORK")
    logo:SetSize(uiConfig.logoSize, uiConfig.logoSize)
    logo:SetPoint("TOPLEFT", 15, uiConfig.headerOffset)
    self:SetCopyBoxIcon(logo)

    local headerText = self.frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightLarge")
    headerText:SetPoint("LEFT", logo, "RIGHT", 8, 0)
    headerText:SetText("|cff66ccffCopyBox|r")

    local headerDivider = self.frame:CreateTexture(nil, "OVERLAY")
    headerDivider:SetColorTexture(1, 1, 1, 0.8)
    headerDivider:SetHeight(uiConfig.dividerHeight)
    headerDivider:SetPoint("TOPLEFT", 15, uiConfig.dividerTopOffset)
    headerDivider:SetPoint("TOPRIGHT", -15, uiConfig.dividerTopOffset)
end

function AIOS_CopyBox_MainFrame:SetCopyBoxIcon(tex)
    if not tex then return end

    local foundTexture = false
    for _, path in ipairs(AIOS_CopyBox_Config.textures.logo) do
        tex:SetTexture(path)
        local currentTexture = tex:GetTexture()
        if currentTexture and currentTexture ~= "" then
            foundTexture = true
            break
        end
    end

    if not foundTexture then
        tex:SetTexture("Interface\\Icons\\INV_Misc_Note_01")
    end

    tex:SetDesaturated(false)
    tex:SetTexCoord(0, 1, 0, 1)
end

function AIOS_CopyBox_MainFrame:CreateScrollFrame()
    local uiConfig = AIOS_CopyBox_Config:GetUIConfig()

    self.scrollFrame = CreateFrame("ScrollFrame", "AIOS_CopyBox_Scroll", self.frame, "UIPanelScrollFrameTemplate")
    self.scrollFrame:SetPoint("TOPLEFT", 15, uiConfig.scrollFrameTopOffset)
    self.scrollFrame:SetPoint("BOTTOMRIGHT", -30, uiConfig.scrollFrameBottomOffset)

    self.editBox = CreateFrame("EditBox", "AIOS_CopyBox_Edit", self.scrollFrame)
    self.editBox:SetMultiLine(true)
    self.editBox:SetFontObject(ChatFontNormal)
    self.editBox:SetWidth(self.scrollFrame:GetWidth() - 20)
    self.editBox:SetHeight(400)
    self.editBox:SetAutoFocus(false)
    self.editBox:SetTextInsets(5, 5, 5, 5)
    self.editBox:SetText("-- Chat messages will appear here --")
    self.editBox:SetHyperlinksEnabled(true)

    self.editBox:SetScript("OnEscapePressed", function(self)
        self:ClearFocus()
        AIOS_CopyBox_MainFrame:Close()
    end)

    if AIOS_CopyBox_ChatManager then
        AIOS_CopyBox_ChatManager:SetEditBox(self.editBox)
    end

    self.scrollFrame:SetScrollChild(self.editBox)

    if self.scrollFrame.ScrollBar then
        self.scrollFrame.ScrollBar:Hide()
        self.scrollFrame.ScrollBar.Show = function() end
    end

    self:RestoreFontSize()
end

function AIOS_CopyBox_MainFrame:CreateFooter()
    local uiConfig = AIOS_CopyBox_Config:GetUIConfig()

    local footerDivider = self.frame:CreateTexture(nil, "OVERLAY")
    footerDivider:SetColorTexture(1, 1, 1, 0.8)
    footerDivider:SetHeight(uiConfig.dividerHeight)
    footerDivider:SetPoint("BOTTOMLEFT", 15, uiConfig.footerDividerOffset)
    footerDivider:SetPoint("BOTTOMRIGHT", -15, uiConfig.footerDividerOffset)

    local btnY = uiConfig.buttonAreaOffset

    -- Channel selector
    self.channelFrame = CreateFrame("Frame", nil, self.frame)
    self.channelFrame:SetSize(160, 20)
    self.channelFrame:SetPoint("BOTTOMLEFT", 15, btnY)
    self.channelFrame:EnableMouse(true)

    self.channelLabel = self.channelFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    self.channelLabel:SetPoint("LEFT", self.channelFrame, "LEFT", 0, -5)
    self.channelLabel:SetText("|cffffffffChannel:|r")

    self.channelValue = self.channelFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    self.channelValue:SetPoint("LEFT", self.channelLabel, "RIGHT", 4, 0)

    function self:UpdateChannelText()
        local name = "General"

        if AIOS_CopyBox_ChatManager then
            local idx = AIOS_CopyBox_ChatManager.currentChatFrame
                or AIOS_CopyBox_ChatManager.lastViewedChannel

            local channels = AIOS_CopyBox_ChatManager.availableChannels
            if channels and idx then
                for _, ch in ipairs(channels) do
                    if ch.id == idx then
                        name = ch.name or name
                        break
                    end
                end
            end
        end

        self.channelValue:SetText("|cff66ccff" .. name .. "|r")
    end

    self:UpdateChannelText()

    self.channelFrame:SetScript("OnMouseDown", function(_, button)
        if not AIOS_CopyBox_ChatManager then return end

        if button == "LeftButton" then
            AIOS_CopyBox_ChatManager:CycleChannels(true)
        elseif button == "RightButton" then
            AIOS_CopyBox_ChatManager:CycleChannels(false)
        end

        self:UpdateChannelText()
    end)

    self.channelFrame:SetScript("OnEnter", function()
        self.channelValue:SetTextColor(0, 1, 0)
        GameTooltip:SetOwner(self.channelFrame, "ANCHOR_TOP")
        GameTooltip:SetText("Channel Selector", 1, 1, 1)
        GameTooltip:AddLine("Left-click: Next channel", 0.4, 0.8, 1, true)
        GameTooltip:AddLine("Right-click: Previous channel", 0.4, 0.8, 1, true)
        GameTooltip:Show()
    end)

    self.channelFrame:SetScript("OnLeave", function()
        self.channelValue:SetTextColor(0.4, 0.8, 1)
        GameTooltip:Hide()
    end)

    -- Select All button
    local selectAll = self.frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    selectAll:SetText("Select All")
    selectAll:SetPoint("BOTTOMLEFT", 170, btnY)
    selectAll:SetTextColor(1, 1, 1, 1)
    selectAll:EnableMouse(true)
    selectAll:SetScript("OnMouseDown", function(_, button)
        if not self.editBox then return end
        if button == "RightButton" then
            self.editBox:SetText("")
            self.editBox:SetFocus()
        else
            self.editBox:SetFocus()
            self.editBox:HighlightText()
        end
    end)
    selectAll:SetScript("OnEnter", function()
        selectAll:SetTextColor(0, 1, 0, 1)
        GameTooltip:SetOwner(selectAll, "ANCHOR_TOP")
        GameTooltip:SetText("Select All", 1, 1, 1)
        GameTooltip:AddLine("Left-click: Select all text", 0.4, 0.8, 1, true)
        GameTooltip:AddLine("Right-click: Clear text", 0.4, 0.8, 1, true)
        GameTooltip:Show()
    end)
    selectAll:SetScript("OnLeave", function()
        selectAll:SetTextColor(1, 1, 1, 1)
        GameTooltip:Hide()
    end)

    -- Settings button
    local settingsBtn = self.frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    settingsBtn:SetText("Settings")
    settingsBtn:SetPoint("BOTTOMLEFT", 260, btnY)
    settingsBtn:SetTextColor(1, 1, 1, 1)
    settingsBtn:EnableMouse(true)
    settingsBtn:SetScript("OnMouseDown", function()
        AIOS_CopyBox_MainFrame:ToggleSettingsPanel()
    end)
    settingsBtn:SetScript("OnEnter", function()
        settingsBtn:SetTextColor(0, 1, 0, 1)
        GameTooltip:SetOwner(settingsBtn, "ANCHOR_TOP")
        GameTooltip:SetText("Settings", 1, 1, 1)
        GameTooltip:AddLine("Click to open settings", 0.4, 0.8, 1, true)
        GameTooltip:Show()
    end)
    settingsBtn:SetScript("OnLeave", function()
        settingsBtn:SetTextColor(1, 1, 1, 1)
        GameTooltip:Hide()
    end)

    -- Theme selector
    self.themeFrame = CreateFrame("Frame", nil, self.frame)
    self.themeFrame:SetSize(150, 20)
    self.themeFrame:SetPoint("BOTTOMLEFT", 360, btnY)

    self.themeLabel = self.themeFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    self.themeLabel:SetPoint("LEFT", self.themeFrame, "LEFT", 0, -5)
    self.themeLabel:SetText("|cffffffffTheme:|r")

    self.themeText = self.themeFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    self.themeText:SetPoint("LEFT", self.themeLabel, "RIGHT", 4, 0)

    local defaultTheme = AIOS_CopyBox_Meta:GetDefaultThemeIndex()
    local defaultThemeName = AIOS_CopyBox_Meta.basicThemes[defaultTheme]
        and AIOS_CopyBox_Meta.basicThemes[defaultTheme].name
        or "Glossy Glass"

    self.themeText:SetText("|cff66ccff" .. defaultThemeName .. "|r")

    self.themeButton = CreateFrame("Button", nil, self.themeFrame)
    self.themeButton:SetPoint("TOPLEFT", self.themeText, "TOPLEFT", -2, 2)
    self.themeButton:SetPoint("BOTTOMRIGHT", self.themeText, "BOTTOMRIGHT", 2, -2)
    self.themeButton:EnableMouse(true)

    self.themeButton:SetScript("OnMouseDown", function(_, button)
        if AIOS_CopyBox_ThemeManager then
            if button == "LeftButton" then
                AIOS_CopyBox_ThemeManager:CycleTheme(true)
            elseif button == "RightButton" then
                AIOS_CopyBox_ThemeManager:CycleTheme(false)
            end
        end
    end)

    self.themeButton:SetScript("OnEnter", function()
        if AIOS_CopyBox_ThemeManager then
            local theme = AIOS_CopyBox_ThemeManager:GetCurrentTheme()
            if theme then
                self.themeText:SetText("|cff00ff00" .. theme.name .. "|r")
            end
        end
        GameTooltip:SetOwner(self.themeButton, "ANCHOR_TOP")
        GameTooltip:SetText("Theme Selector", 1, 1, 1)
        GameTooltip:AddLine("Left-click: Next theme", 0.4, 0.8, 1, true)
        GameTooltip:AddLine("Right-click: Previous theme", 0.4, 0.8, 1, true)
        GameTooltip:Show()
    end)

    self.themeButton:SetScript("OnLeave", function()
        if AIOS_CopyBox_ThemeManager then
            local theme = AIOS_CopyBox_ThemeManager:GetCurrentTheme()
            if theme then
                self.themeText:SetText("|cff66ccff" .. theme.name .. "|r")
            end
        end
        GameTooltip:Hide()
    end)

    -- Open / Close text
    self.openCloseText = self.frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    self.openCloseText:SetText("Open")
    self.openCloseText:SetPoint("BOTTOMRIGHT", -80, btnY)
    self.openCloseText:SetTextColor(1, 1, 1, 1)
    self.openCloseText:EnableMouse(true)

    self.openCloseText:SetScript("OnMouseDown", function()
        self:ToggleSize()
    end)

    self.openCloseText:SetScript("OnEnter", function()
        if self.isExpanded then
            self.openCloseText:SetTextColor(1, 0, 0, 1)
        else
            self.openCloseText:SetTextColor(0, 1, 0, 1)
        end
    end)

    self.openCloseText:SetScript("OnLeave", function()
        self.openCloseText:SetTextColor(1, 1, 1, 1)
    end)

    -- Exit text
    local exitText = self.frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    exitText:SetText("Exit")
    exitText:SetPoint("BOTTOMRIGHT", -15, btnY)
    exitText:SetTextColor(1, 1, 1, 1)
    exitText:EnableMouse(true)

    exitText:SetScript("OnMouseDown", function()
        self:Close()
    end)

    exitText:SetScript("OnEnter", function()
        exitText:SetTextColor(1, 0, 0, 1)
    end)

    exitText:SetScript("OnLeave", function()
        exitText:SetTextColor(1, 1, 1, 1)
    end)

    -- Bottom divider
    local bottomDivider = self.frame:CreateTexture(nil, "OVERLAY")
    bottomDivider:SetColorTexture(1, 1, 1, 0.8)
    bottomDivider:SetHeight(uiConfig.dividerHeight)
    bottomDivider:SetPoint("BOTTOMLEFT", 15, uiConfig.bottomDividerOffset)
    bottomDivider:SetPoint("BOTTOMRIGHT", -15, uiConfig.bottomDividerOffset)

    -- Footer text
    local footerText = self.frame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    footerText:SetText("|cffffffffpowered by |r|cff66ccffAIOS|r")
    footerText:SetPoint("BOTTOM", 0, uiConfig.footerTextOffset)
end

-- ============================================================================
-- Settings Panel (290px tall — fits 3 checkboxes + 2 sliders + buttons)
-- ============================================================================
function AIOS_CopyBox_MainFrame:CreateSettingsPanel()
    if self.settingsPanel then return end

    local panel = CreateFrame("Frame", "AIOS_CopyBox_Settings", UIParent, "BackdropTemplate")
    panel:SetSize(340, 290)
    panel:SetPoint("CENTER")
    panel:SetBackdrop({
        bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        edgeSize = 24,
        insets = { left = 10, right = 10, top = 10, bottom = 10 }
    })
    panel:SetBackdropBorderColor(0.4, 0.6, 0.8, 1)
    panel:SetBackdropColor(0.06, 0.06, 0.12, 0.95)
    panel:SetFrameStrata("FULLSCREEN_DIALOG")
    panel:SetFrameLevel(100)
    panel:EnableMouse(true)
    panel:SetMovable(true)
    panel:RegisterForDrag("LeftButton")
    panel:SetScript("OnDragStart", function(self) self:StartMoving() end)
    panel:SetScript("OnDragStop", function(self) self:StopMovingOrSizing() end)
    panel:Hide()

    local gloss = panel:CreateTexture(nil, "BACKGROUND", nil, 1)
    gloss:SetTexture("Interface\\Buttons\\WHITE8x8")
    gloss:SetBlendMode("ADD")
    gloss:SetVertexColor(0.8, 0.9, 1.0, 0.08)
    gloss:SetAllPoints(panel)

    local headerBar = panel:CreateTexture(nil, "BORDER")
    headerBar:SetColorTexture(0.15, 0.25, 0.45, 0.6)
    headerBar:SetHeight(32)
    headerBar:SetPoint("TOPLEFT", 10, -10)
    headerBar:SetPoint("TOPRIGHT", -10, -10)

    local title = panel:CreateFontString(nil, "OVERLAY", "GameFontHighlightLarge")
    title:SetText("|cff66ccffCopyBox Settings|r")
    title:SetPoint("TOP", 0, -18)

    local closeBtn = CreateFrame("Button", nil, panel)
    closeBtn:SetSize(20, 20)
    closeBtn:SetPoint("TOPRIGHT", -12, -12)
    closeBtn:SetNormalTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Up")
    closeBtn:SetPushedTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Down")
    closeBtn:SetHighlightTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Highlight")
    closeBtn:SetScript("OnClick", function()
        panel:Hide()
    end)

    local divider = panel:CreateTexture(nil, "OVERLAY")
    divider:SetColorTexture(0.4, 0.6, 0.8, 0.8)
    divider:SetHeight(2)
    divider:SetPoint("TOPLEFT", 20, -48)
    divider:SetPoint("TOPRIGHT", -20, -48)

    -- Font Size
    local fontLabel = panel:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    fontLabel:SetText("|cffffffffFont Size:|r")
    fontLabel:SetPoint("TOPLEFT", 25, -65)

    local fontValue = panel:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    fontValue:SetPoint("LEFT", fontLabel, "RIGHT", 10, 0)
    fontValue:SetTextColor(0.4, 0.8, 1, 1)

    local fontSlider = CreateFrame("Slider", "AIOS_CopyBox_FontSlider", panel, "OptionsSliderTemplate")
    fontSlider:SetPoint("TOPLEFT", 25, -86)
    fontSlider:SetWidth(290)
    fontSlider:SetHeight(14)
    fontSlider:SetMinMaxValues(8, 20)
    fontSlider:SetValueStep(1)
    fontSlider:SetObeyStepOnDrag(true)

    local fontThumb = fontSlider:GetThumbTexture()
    if fontThumb then
        fontThumb:SetWidth(14)
        fontThumb:SetHeight(18)
        fontThumb:SetColorTexture(0.4, 0.8, 1, 1)
    end

    _G[fontSlider:GetName() .. "Low"]:SetText("|cffaaaaaa8|r")
    _G[fontSlider:GetName() .. "High"]:SetText("|cffaaaaaa20|r")
    _G[fontSlider:GetName() .. "Text"]:SetText("")

    local currentFontSize = 12
    if self.editBox then
        local _, size = self.editBox:GetFont()
        if size then currentFontSize = size end
    end
    fontSlider:SetValue(currentFontSize)
    fontValue:SetText(tostring(currentFontSize))

    fontSlider:SetScript("OnValueChanged", function(_, value)
        local size = math.floor(value + 0.5)
        fontValue:SetText(tostring(size))
        AIOS_CopyBox_MainFrame:SetFontSize(size)
    end)

    -- Max Lines
    local linesLabel = panel:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    linesLabel:SetText("|cffffffffMax Lines:|r")
    linesLabel:SetPoint("TOPLEFT", 25, -110)

    local linesValue = panel:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    linesValue:SetPoint("LEFT", linesLabel, "RIGHT", 10, 0)
    linesValue:SetTextColor(0.4, 0.8, 1, 1)

    local linesSlider = CreateFrame("Slider", "AIOS_CopyBox_LinesSlider", panel, "OptionsSliderTemplate")
    linesSlider:SetPoint("TOPLEFT", 25, -131)
    linesSlider:SetWidth(290)
    linesSlider:SetHeight(14)
    linesSlider:SetMinMaxValues(50, 1000)
    linesSlider:SetValueStep(50)
    linesSlider:SetObeyStepOnDrag(true)

    local linesThumb = linesSlider:GetThumbTexture()
    if linesThumb then
        linesThumb:SetWidth(14)
        linesThumb:SetHeight(18)
        linesThumb:SetColorTexture(0.4, 0.8, 1, 1)
    end

    _G[linesSlider:GetName() .. "Low"]:SetText("|cffaaaaaa50|r")
    _G[linesSlider:GetName() .. "High"]:SetText("|cffaaaaaa1000|r")
    _G[linesSlider:GetName() .. "Text"]:SetText("")

    local currentMaxLines = AIOS_CopyBox_Config.chat.maxLines
    linesSlider:SetValue(currentMaxLines)
    linesValue:SetText(tostring(currentMaxLines))

    linesSlider:SetScript("OnValueChanged", function(_, value)
        local lines = math.floor((value / 50) + 0.5) * 50
        linesValue:SetText(tostring(lines))
        AIOS_CopyBox_Config.chat.maxLines = lines
        if AIOS_CopyBoxDB then
            AIOS_CopyBoxDB.maxLines = lines
        end
    end)

    -- Checkbox helper
    local function CreateCheckbox(parent, labelText, yPos, dbKey, onToggle)
        local cb = CreateFrame("CheckButton", "AIOS_CopyBox_CB_" .. dbKey, parent, "UICheckButtonTemplate")
        cb:SetSize(22, 22)
        cb:SetPoint("TOPLEFT", 25, yPos)

        local label = parent:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        label:SetText("|cffffffff" .. labelText .. "|r")
        label:SetPoint("LEFT", cb, "RIGHT", 6, 0)

        local isChecked = AIOS_CopyBoxDB and AIOS_CopyBoxDB[dbKey] or false
        cb:SetChecked(isChecked)

        cb:SetScript("OnClick", function(self)
            local checked = self:GetChecked()
            AIOS_CopyBoxDB[dbKey] = checked
            if onToggle then
                onToggle(checked)
            end
        end)

        return cb
    end

    -- Lock Scroll
    CreateCheckbox(panel, "Lock Scroll (no auto-scroll)", -155, "lockScroll")

    -- Timestamps
    CreateCheckbox(panel, "Show Timestamps", -180, "showTimestamps")

    -- Live Updates
    CreateCheckbox(panel, "Enable Live Updates", -205, "enableLiveUpdates", function(checked)
        AIOS_CopyBox_Config.behavior.enableLiveUpdates = checked
        if checked and AIOS_CopyBox_ChatManager then
            AIOS_CopyBox_ChatManager:HookChatFramesForLiveUpdates()
        end
    end)

    -- Reset button
    local resetBtn = CreateFrame("Button", nil, panel, "UIPanelButtonTemplate")
    resetBtn:SetSize(100, 24)
    resetBtn:SetPoint("BOTTOMLEFT", 25, 15)
    resetBtn:SetText("Reset")
    resetBtn:SetScript("OnClick", function()
        AIOS_CopyBoxDB.fontSize = 13
        AIOS_CopyBoxDB.maxLines = 500
        AIOS_CopyBoxDB.lockScroll = false
        AIOS_CopyBoxDB.showTimestamps = false
        AIOS_CopyBoxDB.enableLiveUpdates = true

        fontSlider:SetValue(13)
        linesSlider:SetValue(500)

        for _, child in ipairs({panel:GetChildren()}) do
            if child:IsObjectType("CheckButton") and child:GetName() then
                local name = child:GetName()
                if name == "AIOS_CopyBox_CB_lockScroll" then
                    child:SetChecked(false)
                elseif name == "AIOS_CopyBox_CB_showTimestamps" then
                    child:SetChecked(false)
                elseif name == "AIOS_CopyBox_CB_enableLiveUpdates" then
                    child:SetChecked(true)
                end
            end
        end
    end)

    -- Close button
    local closeBtn2 = CreateFrame("Button", nil, panel, "UIPanelButtonTemplate")
    closeBtn2:SetSize(100, 24)
    closeBtn2:SetPoint("BOTTOMRIGHT", -25, 15)
    closeBtn2:SetText("Close")
    closeBtn2:SetScript("OnClick", function()
        panel:Hide()
    end)

    self.settingsPanel = panel
    self.settingsFontSlider = fontSlider
    self.settingsFontValue = fontValue
    self.settingsLinesSlider = linesSlider
    self.settingsLinesValue = linesValue
end

function AIOS_CopyBox_MainFrame:ToggleSettingsPanel()
    if not self.settingsPanel then
        self:CreateSettingsPanel()
    end

    if self.settingsPanel:IsShown() then
        self.settingsPanel:Hide()
    else
        -- Refresh sliders
        if self.editBox and self.settingsFontSlider and self.settingsFontValue then
            local _, currentSize = self.editBox:GetFont()
            if currentSize then
                self.settingsFontSlider:SetValue(currentSize)
                self.settingsFontValue:SetText(tostring(math.floor(currentSize + 0.5)))
            end
        end
        if self.settingsLinesSlider and self.settingsLinesValue then
            local currentLines = AIOS_CopyBox_Config.chat.maxLines
            self.settingsLinesSlider:SetValue(currentLines)
            self.settingsLinesValue:SetText(tostring(currentLines))
        end

        -- Refresh checkboxes
        for _, child in ipairs({self.settingsPanel:GetChildren()}) do
            if child:IsObjectType("CheckButton") and child:GetName() then
                local name = child:GetName()
                if name == "AIOS_CopyBox_CB_lockScroll" then
                    child:SetChecked(AIOS_CopyBoxDB and AIOS_CopyBoxDB.lockScroll or false)
                elseif name == "AIOS_CopyBox_CB_showTimestamps" then
                    child:SetChecked(AIOS_CopyBoxDB and AIOS_CopyBoxDB.showTimestamps or false)
                elseif name == "AIOS_CopyBox_CB_enableLiveUpdates" then
                    child:SetChecked(AIOS_CopyBoxDB and AIOS_CopyBoxDB.enableLiveUpdates ~= false)
                end
            end
        end

        self.settingsPanel:Show()
    end
end

function AIOS_CopyBox_MainFrame:SetFontSize(size)
    if not self.editBox then return end
    local fontFile, _, fontFlags = self.editBox:GetFont()
    if fontFile then
        self.editBox:SetFont(fontFile, size, fontFlags)
    end
    if AIOS_CopyBoxDB then
        AIOS_CopyBoxDB.fontSize = size
    end
end

function AIOS_CopyBox_MainFrame:RestoreFontSize()
    if not AIOS_CopyBoxDB or not AIOS_CopyBoxDB.fontSize then return end
    if not self.editBox then return end
    local fontFile, _, fontFlags = self.editBox:GetFont()
    if fontFile then
        self.editBox:SetFont(fontFile, AIOS_CopyBoxDB.fontSize, fontFlags)
    end
end

function AIOS_CopyBox_MainFrame:RestoreMaxLines()
    if not AIOS_CopyBoxDB or not AIOS_CopyBoxDB.maxLines then return end
    AIOS_CopyBox_Config.chat.maxLines = AIOS_CopyBoxDB.maxLines
end

function AIOS_CopyBox_MainFrame:Open(chatFrameId, maxLines)
    if not self.frame then
        self:Initialize()
    end

    if self.frame then
        self.frame:Show()

        if AIOS_CopyBox_ThemeManager then
            AIOS_CopyBox_ThemeManager:ApplyCurrentTheme()
        end
    end
end

function AIOS_CopyBox_MainFrame:Close()
    if self.editBox then
        self.editBox:ClearFocus()
    end
    if self.frame then
        self.frame:Hide()
    end
    if self.settingsPanel then
        self.settingsPanel:Hide()
    end
end

function AIOS_CopyBox_MainFrame:ToggleSize()
    local frameConfig = AIOS_CopyBox_Config:GetFrameConfig()
    self.isExpanded = not self.isExpanded

    local newHeight = self.isExpanded and frameConfig.expandedHeight or frameConfig.originalHeight
    self.frame:SetHeight(newHeight)

    if self.openCloseText then
        if self.isExpanded then
            self.openCloseText:SetText("Close")
        else
            self.openCloseText:SetText("Open")
        end
    end

    if AIOS_CopyBox_ThemeManager then
        AIOS_CopyBox_ThemeManager:ApplyCurrentTheme()
    end
end

function AIOS_CopyBox_MainFrame:RefreshTheme()
    if self.frame then
        local width, height = self.frame:GetSize()
        self.frame:SetSize(width, height)

        if self.frame:GetScript("OnSizeChanged") then
            self.frame:GetScript("OnSizeChanged")(self.frame)
        end
    end
end

function AIOS_CopyBox_MainFrame:SavePosition()
    if not AIOS_CopyBoxDB or not self.frame then return end
    local point, _, relPoint, x, y = self.frame:GetPoint()
    AIOS_CopyBoxDB.framePos = {
        point = point,
        relPoint = relPoint,
        x = x,
        y = y
    }
end

function AIOS_CopyBox_MainFrame:RestorePosition()
    if not AIOS_CopyBoxDB or not AIOS_CopyBoxDB.framePos or not self.frame then return end
    local p = AIOS_CopyBoxDB.framePos
    self.frame:ClearAllPoints()
    self.frame:SetPoint(p.point or "CENTER", UIParent, p.relPoint or "CENTER", p.x or 0, p.y or 0)
end

function AIOS_CopyBox_MainFrame:ApplyBackgroundTexture(texturePath, scaleX, scaleY, position)
    if not self.background then return end

    if texturePath then
        self.background:SetTexture(texturePath)
        self.background:SetTexCoord(0, 1, 0, 1)
        self.background:SetVertexColor(1, 1, 1, 1)
        self.background:SetHorizTile(false)
        self.background:SetVertTile(false)
        self.background:SetDesaturated(false)

        self.background:ClearAllPoints()

        if scaleX ~= 1.0 or scaleY ~= 1.0 then
            local frameWidth, frameHeight = self.frame:GetWidth(), self.frame:GetHeight()
            self.background:SetSize(frameWidth * scaleX, frameHeight * scaleY)
            self.background:SetPoint(position or "CENTER", self.frame, position or "CENTER", 0, 0)
        else
            self.background:SetAllPoints(self.frame)
        end

        if self.glossTexture then
            self.glossTexture:ClearAllPoints()
            if scaleX ~= 1.0 or scaleY ~= 1.0 then
                local frameWidth, frameHeight = self.frame:GetWidth(), self.frame:GetHeight()
                self.glossTexture:SetSize(frameWidth * scaleX, frameHeight * scaleY)
                self.glossTexture:SetPoint(position or "CENTER", self.frame, position or "CENTER", 0, 0)
            else
                self.glossTexture:SetAllPoints(self.frame)
            end
        end
    else
        self.background:ClearAllPoints()
        self.background:SetAllPoints(self.frame)
        self.background:SetColorTexture(0.1, 0.1, 0.2, 0.9)

        if self.glossTexture then
            self.glossTexture:ClearAllPoints()
            self.glossTexture:SetAllPoints(self.frame)
        end
    end
end

function AIOS_CopyBox_MainFrame:ApplyBackgroundColor(r, g, b, a)
    if not self.background then return end

    self.background:ClearAllPoints()
    self.background:SetAllPoints(self.frame)
    self.background:SetColorTexture(r, g, b, a)

    if self.glossTexture then
        self.glossTexture:ClearAllPoints()
        self.glossTexture:SetAllPoints(self.frame)
    end
end

function AIOS_CopyBox_MainFrame:SetBorderVisibility(visible)
    local isClassic = WOW_PROJECT_ID == WOW_PROJECT_CLASSIC

    if not isClassic and self.borderFrame then
        self.borderFrame:SetShown(visible)
    elseif isClassic and self.borderTextures then
        for _, texture in ipairs(self.borderTextures) do
            texture:SetShown(visible)
        end
    end
end

function AIOS_CopyBox_MainFrame:SetBorderColor(r, g, b, a)
    local isClassic = WOW_PROJECT_ID == WOW_PROJECT_CLASSIC

    if not isClassic and self.borderFrame then
        self.borderFrame:SetBackdropBorderColor(r, g, b, a)
    elseif isClassic and self.borderTextures then
        for _, texture in ipairs(self.borderTextures) do
            texture:SetVertexColor(r, g, b, a)
        end
    end
end

function AIOS_CopyBox_MainFrame:SetGlossColor(r, g, b, a)
    if self.glossTexture then
        self.glossTexture:SetVertexColor(r, g, b, a)
    end
end