local addonName, RF = ...

-------------------------------------------------------------------------------
-- ExportEngine: CSV and text export with copyable popup
-------------------------------------------------------------------------------

-------------------------------------------------------------------------------
-- Export data in specified format
-------------------------------------------------------------------------------
function RF:ExportData(entries, fmt)
    entries = entries or RF.rosterData
    fmt = fmt or "csv"

    if #entries == 0 then
        RF:Print("No data to export.")
        return
    end

    local output
    if fmt == "csv" then
        output = RF:ExportCSV(entries)
    else
        output = RF:ExportText(entries)
    end

    RF:ShowExportPopup(output)
end

-------------------------------------------------------------------------------
-- CSV Export
-------------------------------------------------------------------------------
function RF:ExportCSV(entries)
    local lines = {}

    -- Header
    tinsert(lines, "Name,Rank,RankIndex,Level,Class,Zone,Note,OfficerNote,LastOnline,Status,JoinDate,AltMain")

    for _, e in ipairs(entries) do
        local fields = {
            RF:CSVEscape(e.name),
            RF:CSVEscape(e.rankName),
            tostring(e.rankIndex),
            tostring(e.level),
            RF:CSVEscape(e.classDisplayName or ""),
            RF:CSVEscape(e.zone),
            RF:CSVEscape(e.note),
            RF:CSVEscape(e.officerNote),
            RF:CSVEscape(e.lastOnlineText or ""),
            RF:CSVEscape(e.status),
            RF:CSVEscape(e.joinDate or ""),
            RF:CSVEscape(e.altMain or ""),
        }
        tinsert(lines, table.concat(fields, ","))
    end

    return table.concat(lines, "\n")
end

-------------------------------------------------------------------------------
-- Text Export
-------------------------------------------------------------------------------
function RF:ExportText(entries)
    local lines = {}

    tinsert(lines, format("RosterForge Export - %s - %d members", RF:GetGuildKey() or "Unknown Guild", #entries))
    tinsert(lines, string.rep("-", 60))

    for _, e in ipairs(entries) do
        local line = format("%-20s %-15s Lvl%-3d %-12s %s",
            e.name,
            e.rankName,
            e.level,
            e.classDisplayName or "",
            e.lastOnlineText or ""
        )
        if e.note and e.note ~= "" then
            line = line .. " | Note: " .. e.note
        end
        tinsert(lines, line)
    end

    tinsert(lines, string.rep("-", 60))
    tinsert(lines, format("Total: %d members", #entries))

    return table.concat(lines, "\n")
end

-------------------------------------------------------------------------------
-- CSV Escape
-------------------------------------------------------------------------------
function RF:CSVEscape(str)
    str = tostring(str or "")
    if str:find('[,"\n]') then
        return '"' .. str:gsub('"', '""') .. '"'
    end
    return str
end

-------------------------------------------------------------------------------
-- Export Popup (large copyable text area)
-------------------------------------------------------------------------------
function RF:ShowExportPopup(text)
    if not RF.exportFrame then
        local f = RF:CreateStyledFrame("RosterForgeExport", UIParent, 600, 400, {
            title = "Export Data",
            closable = true,
            strata = "DIALOG",
        })
        f:SetPoint("CENTER")
        f:Hide()

        local scroll = CreateFrame("ScrollFrame", nil, f, "UIPanelScrollFrameTemplate")
        scroll:SetPoint("TOPLEFT", f.titleBar, "BOTTOMLEFT", 8, -8)
        scroll:SetPoint("BOTTOMRIGHT", -28, 36)

        local eb = CreateFrame("EditBox", nil, scroll)
        eb:SetWidth(555)
        eb:SetFontObject("ChatFontNormal")
        eb:SetFont(eb:GetFont(), 11, "")
        eb:SetTextColor(unpack(RF.Theme.textPrimary))
        eb:SetMultiLine(true)
        eb:SetAutoFocus(false)
        eb:SetScript("OnEscapePressed", function() f:Hide() end)
        scroll:SetScrollChild(eb)
        f.editBox = eb

        -- Select All button
        local selectAllBtn = RF:CreateButton(f, "Select All", 80, 24, "accent")
        selectAllBtn:SetPoint("BOTTOMLEFT", 8, 8)
        selectAllBtn:SetScript("OnClick", function()
            eb:SetFocus()
            eb:HighlightText()
        end)

        -- Close button
        local closeBtn = RF:CreateButton(f, "Close", 60, 24)
        closeBtn:SetPoint("BOTTOMRIGHT", -8, 8)
        closeBtn:SetScript("OnClick", function() f:Hide() end)

        RF.exportFrame = f
    end

    RF.exportFrame.editBox:SetText(text)
    RF.exportFrame:Show()
    RF.exportFrame.editBox:SetFocus()
    RF.exportFrame.editBox:HighlightText()
    RF:Print(format("Export ready - %d characters. Select all and copy.", #text))
end
