local addonName, NS = ...
local GR = _G["GRS_MainFrame"]

-- Import Helpers from Core
local CreateBg = GR.RR.CreateBg
local SkinButton = GR.RR.SkinButton
local GetFullPlayerName = GR.RR.GetFullPlayerName

-- =========================================================================
-- UTF-8 DECODER
-- =========================================================================
local function FixUTF8(s)
    if not s then return "" end
    local mapping = {
        ["Ã¨"] = "è", ["Ã¡"] = "á", ["Ã©"] = "é", ["Ã³"] = "ó", ["Ãº"] = "ú",
        ["Ã±"] = "ñ", ["Ã "] = "à", ["Ã¢"] = "â", ["Ãª"] = "ê", ["Ã®"] = "î",
        ["Ã´"] = "ô", ["Ã»"] = "û", ["Ã«"] = "ë", ["Ã¯"] = "ï", ["Ã¼"] = "ü"
    }
    for k, v in pairs(mapping) do
        s = s:gsub(k, v)
    end
    return s
end

-- =========================================================================
-- LOGIC: WCL IMPORT DIALOG
-- =========================================================================

function GR:RR_OpenImportDialog()
    if self.ImportDialog then 
        self.ImportDialog:Show() 
        self:RR_RefreshImportDropdown()
        return 
    end

    local f = CreateFrame("Frame", "GRS_RR_ImportDialog", UIParent, "BackdropTemplate")
    f:SetSize(400, 450)
    f:SetPoint("CENTER")
    f:SetFrameStrata("FULLSCREEN_DIALOG")
    f:SetFrameLevel(100)
    
    f:SetMovable(true); f:EnableMouse(true); f:RegisterForDrag("LeftButton")
    f:SetScript("OnDragStart", f.StartMoving)
    f:SetScript("OnDragStop", f.StopMovingOrSizing)

    CreateBg(f, 0.05, 0.05, 0.1, 0.95)
    GR.RR.CreateBorder(f, 0.5, 0.5, 0.5, 1)

    local title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOP", 0, -15); title:SetText("Import Warcraft Logs")
    
    -- Close button
    local closeBtn = CreateFrame("Button", nil, f)
    closeBtn:SetSize(24, 24); closeBtn:SetPoint("TOPRIGHT", -5, -5)
    SkinButton(closeBtn)
    local closeFs = closeBtn:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    closeFs:SetPoint("CENTER"); closeFs:SetText("X")
    closeBtn:SetFontString(closeFs)
    closeBtn:SetScript("OnClick", function() f:Hide() end)

    local ddLabel = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    ddLabel:SetPoint("TOPLEFT", 30, -50); ddLabel:SetText("Select Target Event:")

    local dd = CreateFrame("Button", nil, f)
    dd:SetSize(340, 24); dd:SetPoint("TOPLEFT", 30, -65)
    CreateBg(dd, 0, 0, 0, 0.6)
    
    local ddTxt = dd:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    ddTxt:SetPoint("LEFT", 10, 0); ddTxt:SetText("Choose an event...")
    dd.text = ddTxt
    f.dd = dd 

    local arrow = dd:CreateTexture(nil, "ARTWORK")
    arrow:SetTexture("Interface\\Buttons\\UI-ScrollBar-ScrollDownButton-Up")
    arrow:SetSize(16, 16); arrow:SetPoint("RIGHT", -5, 0)

    local ddList = CreateFrame("Frame", nil, dd, "BackdropTemplate")
    ddList:SetSize(340, 100); ddList:SetPoint("TOPLEFT", dd, "BOTTOMLEFT", 0, -2)
    ddList:SetFrameStrata("TOOLTIP"); CreateBg(ddList, 0, 0, 0, 1)
    ddList:Hide()
    f.ddList = ddList

    dd:SetScript("OnClick", function() ddList:SetShown(not ddList:IsShown()) end)

    local inLabel = f:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    inLabel:SetPoint("TOPLEFT", 30, -105); inLabel:SetText("Paste WCL CSV Data below:")

    local inFrame = CreateFrame("Frame", nil, f, "BackdropTemplate")
    inFrame:SetSize(340, 220); inFrame:SetPoint("TOPLEFT", 30, -120)
    CreateBg(inFrame, 0, 0, 0, 0.6)

    local scrollIn = CreateFrame("ScrollFrame", nil, inFrame, "UIPanelScrollFrameTemplate")
    scrollIn:SetPoint("TOPLEFT", 5, -5); scrollIn:SetPoint("BOTTOMRIGHT", -25, 5)
    if NS.StyleScrollBar then NS.StyleScrollBar(scrollIn) end

    local editIn = CreateFrame("EditBox", nil, scrollIn)
    editIn:SetMultiLine(true); editIn:SetSize(310, 210); editIn:SetFontObject(ChatFontNormal)
    editIn:SetAutoFocus(false); editIn:SetMaxLetters(0)
    editIn:SetScript("OnEscapePressed", function(s) s:ClearFocus() end)
    scrollIn:SetScrollChild(editIn)
    f.editIn = editIn

    local btnImp = CreateFrame("Button", nil, f)
    btnImp:SetSize(120, 30); btnImp:SetPoint("BOTTOMLEFT", 40, 30)
    local btnImpFs = btnImp:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    btnImpFs:SetPoint("CENTER"); btnImpFs:SetText("IMPORT")
    btnImp:SetFontString(btnImpFs)
    SkinButton(btnImp)
    btnImp:Disable()
    btnImpFs:SetTextColor(1, 0.2, 0.2) 

    local btnCancel = CreateFrame("Button", nil, f)
    btnCancel:SetSize(120, 30); btnCancel:SetPoint("BOTTOMRIGHT", -40, 30)
    local btnCancelFs = btnCancel:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    btnCancelFs:SetPoint("CENTER"); btnCancelFs:SetText("CANCEL")
    btnCancel:SetFontString(btnCancelFs)
    SkinButton(btnCancel)
    btnCancel:SetScript("OnClick", function() f:Hide() end)

    local function ValidateInput()
        local txt = editIn:GetText() or ""
        local hasHeader = string.find(txt, "Name")
        local hasData = string.find(txt, "\"[^\"]*\"")
        
        if f.selectedEventID and hasHeader and hasData then
            btnImp:Enable()
            btnImpFs:SetTextColor(0.2, 1, 0.2) 
        else
            btnImp:Disable()
            btnImpFs:SetTextColor(1, 0.2, 0.2)
        end
    end

    editIn:SetScript("OnTextChanged", ValidateInput)

    btnImp:SetScript("OnClick", function()
        self:RR_ProcessWCLImport(f.selectedEventID, editIn:GetText())
        f:Hide()
        editIn:SetText("")
    end)

    self.ImportDialog = f
    self:RR_RefreshImportDropdown()
end

function GR:RR_RefreshImportDropdown()
    local f = self.ImportDialog
    if not f then return end
    
    local list = f.ddList
    local kids = {list:GetChildren()}
    for _, k in ipairs(kids) do k:Hide() end

    local sortedIDs = GR:RR_GetSortedEventIDs(20)
    local y = -5
    for _, eid in ipairs(sortedIDs) do
        local evt = GRS_RaidRosterDB.events[eid]
        if evt then
            local b = CreateFrame("Button", nil, list)
            b:SetSize(330, 20); b:SetPoint("TOPLEFT", 5, y)
            local t = b:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
            t:SetPoint("LEFT", 5, 0); t:SetText(string.format("[%s] %s", evt.date or "??", evt.name or "Untitled"))
            
            b:SetScript("OnClick", function()
                f.selectedEventID = eid
                f.dd.text:SetText(t:GetText())
                list:Hide()
                if f.editIn:GetScript("OnTextChanged") then f.editIn:GetScript("OnTextChanged")(f.editIn) end
            end)
            b:Show()
            y = y - 22
        end
    end
    list:SetHeight(math.max(math.abs(y) + 5, 20))
end

function GR:RR_ProcessWCLImport(evtID, csvData)
    if not evtID or not csvData then return end
    
    -- TBC: Use GuildRoster() instead of C_GuildInfo.GuildRoster()
    if _G.GuildRoster then _G.GuildRoster() end
    
    local guildNames = {}
    local num = GetNumGuildMembers()
    for i = 1, num do
        local fullName = GetGuildRosterInfo(i)
        if fullName then
            local clean = Ambiguate(fullName, "none")
            guildNames[clean] = clean
        end
    end

    local nameColIndex = nil
    local importedCount = 0
    local discardedCount = 0
    local me = GetFullPlayerName()
    local targetEvt = GRS_RaidRosterDB.events[evtID]
    local eventLabel = targetEvt and string.format("[%s] %s", targetEvt.date, targetEvt.name) or evtID

    for line in csvData:gmatch("[^\r\n]+") do
        local columns = {}
        for col in line:gmatch('"([^"]*)"') do
            table.insert(columns, col)
        end

        if not nameColIndex then
            for i, colName in ipairs(columns) do
                if colName == "Name" then nameColIndex = i break end
            end
        else
            local rawName = columns[nameColIndex]
            if rawName and rawName ~= "" then
                local cleanName = FixUTF8(rawName)
                local targetName = Ambiguate(cleanName, "none")

                if guildNames[targetName] then
                    GR:RR_UpdateMemberStatus(evtID, targetName, "DPS", "PRESENT", GetServerTime())
                    importedCount = importedCount + 1
                else
                    discardedCount = discardedCount + 1
                end
            end
        end
    end

    GR:RR_AddLogEntry(me, string.format("WCL IMPORT: Synced %d players (names only) for %s.", importedCount, eventLabel))
    print(string.format("|cff00ff00GRS:|r WCL Import Complete. |cffffd100%d|r mains recorded. |cffaaaaaa%d|r skipped.", importedCount, discardedCount))
    
    if GR.RR.trackingPanels then
        for _, p in pairs(GR.RR.trackingPanels) do p.Update() end
    end
end
