local addonName, TC = ...
TC.ChatCopy = {}

function TC.ChatCopy:CreateFrame()
    if self.Frame then return end

    -- Using the standard PortraitFrameTemplate to match the rest of your UI
    local f = CreateFrame("Frame", "TownCrierChatCopyFrame", UIParent, "PortraitFrameTemplate")
    f:SetSize(500, 450)
    f:SetPoint("CENTER")
    f:SetMovable(true)
    f:EnableMouse(true)
    f:RegisterForDrag("LeftButton")
    f:SetScript("OnDragStart", f.StartMoving)
    f:SetScript("OnDragStop", f.StopMovingOrSizing)
    f:Hide()

    if f.SetTitle then f:SetTitle("TownCrier: Chat Ledger") end
    if f.SetPortraitToAsset then f:SetPortraitToAsset("Interface\\Icons\\INV_Scroll_03") end

    -- Standard ScrollFrame setup
    local sf = CreateFrame("ScrollFrame", "TownCrierChatCopyScroll", f, "UIPanelScrollFrameTemplate")
    sf:SetPoint("TOPLEFT", 20, -60)
    sf:SetPoint("BOTTOMRIGHT", -35, 20)

    -- Fixed Backdrop: Matches your Sunblessed Gold theme
    local bg = CreateFrame("Frame", nil, f, "BackdropTemplate")
    bg:SetPoint("TOPLEFT", sf, -5, 5)
    bg:SetPoint("BOTTOMRIGHT", sf, 25, -5)
    bg:SetBackdrop({
        bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        tile = true, tileSize = 16, edgeSize = 16,
        insets = { left = 3, right = 3, top = 3, bottom = 3 }
    })
    bg:SetBackdropColor(0, 0, 0, 1.0) 
    bg:SetBackdropBorderColor(1, 0.82, 0, 1) -- Sunblessed Gold

    sf:SetFrameLevel(bg:GetFrameLevel() + 1)

    local eb = CreateFrame("EditBox", nil, sf)
    eb:SetMultiLine(true)
    eb:SetFontObject("GameFontHighlight") 
    eb:SetTextColor(1, 1, 1, 1) 
    eb:SetSize(430, 370) 
    eb:SetAutoFocus(false)
    sf:SetScrollChild(eb)

    eb:SetScript("OnEscapePressed", function() 
        eb:ClearFocus()
        f:Hide() 
    end)

    self.EditBox = eb
    self.Frame = f
end

function TC.ChatCopy:GetChatLines()
    local text = ""
    for i = 1, ChatFrame1:GetNumMessages() do
        local msg = ChatFrame1:GetMessageInfo(i)
        if msg then
            -- Strips colors and links for easy clipboard use
            local cleanMsg = msg:gsub("|c%x%x%x%x%x%x%x%x", ""):gsub("|r", ""):gsub("|H.-|h(.-)|h", "%1")
            text = text .. cleanMsg .. "\n"
        end
    end
    return text
end

function TC.ChatCopy:Toggle()
    if not self.Frame then self:CreateFrame() end
    
    if self.Frame:IsShown() then
        self.Frame:Hide()
    else
        self.EditBox:SetText(self:GetChatLines())
        self.EditBox:SetCursorPosition(string.len(self.EditBox:GetText()))
        self.Frame:Show()
    end
end