local addonName, RF = ...
local T

local detailPanel = nil
local currentData = nil

-------------------------------------------------------------------------------
-- Class icon texture coordinates
-------------------------------------------------------------------------------
local CLASS_ICON_COORDS = {
    WARRIOR     = { 0.00, 0.25, 0.00, 0.25 },
    MAGE        = { 0.25, 0.50, 0.00, 0.25 },
    ROGUE       = { 0.50, 0.75, 0.00, 0.25 },
    DRUID       = { 0.75, 1.00, 0.00, 0.25 },
    HUNTER      = { 0.00, 0.25, 0.25, 0.50 },
    SHAMAN      = { 0.25, 0.50, 0.25, 0.50 },
    PRIEST      = { 0.50, 0.75, 0.25, 0.50 },
    WARLOCK     = { 0.75, 1.00, 0.25, 0.50 },
    PALADIN     = { 0.00, 0.25, 0.50, 0.75 },
    DEATHKNIGHT = { 0.25, 0.50, 0.50, 0.75 },
    MONK        = { 0.50, 0.75, 0.50, 0.75 },
    DEMONHUNTER = { 0.75, 1.00, 0.50, 0.75 },
    EVOKER      = { 0.00, 0.25, 0.75, 1.00 },
}

local GUILD_REP_LABELS = {
    [4] = "Neutral",
    [5] = "Friendly",
    [6] = "Honored",
    [7] = "Revered",
    [8] = "Exalted",
}

-------------------------------------------------------------------------------
-- Helper: create a labeled info row
-------------------------------------------------------------------------------
local function CreateInfoRow(parent, y)
    local label = RF:CreateLabel(parent, "", RF.FONT_SIZES.normal, "textSecondary")
    label:SetPoint("TOPLEFT", 12, y)
    label:SetPoint("RIGHT", -12, 0)
    label:SetJustifyH("LEFT")
    label:SetWordWrap(true)
    return label
end

local function CreateSectionHeader(parent, text, y)
    local label = RF:CreateLabel(parent, text, RF.FONT_SIZES.small, "textMuted")
    label:SetPoint("TOPLEFT", 12, y)
    return label
end

local function CreateDividerAt(parent, y)
    local div = RF:CreateDivider(parent)
    div:SetPoint("TOPLEFT", 8, y)
    div:SetPoint("TOPRIGHT", -8, y)
    return div
end

-------------------------------------------------------------------------------
-- Create Detail Panel (300px slide-out on right side of main frame)
-------------------------------------------------------------------------------
local function CreateDetailPanel()
    T = RF.Theme

    local parent = RF.mainFrame
    if not parent then return end

    local panel = CreateFrame("Frame", "RosterForgeDetailPanel", UIParent, "BackdropTemplate")
    panel:SetWidth(300)
    panel:SetPoint("TOPLEFT", parent, "TOPRIGHT", -1, 0)
    panel:SetPoint("BOTTOMLEFT", parent, "BOTTOMRIGHT", -1, 0)
    panel:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Buttons\\WHITE8x8",
        edgeSize = 1,
    })
    panel:SetBackdropColor(unpack(T.bgSecondary))
    panel:SetBackdropBorderColor(unpack(T.border))
    panel:SetFrameStrata(parent:GetFrameStrata())
    panel:SetFrameLevel(parent:GetFrameLevel() + 2)
    panel:SetClampedToScreen(true)
    panel:Hide()

    parent:HookScript("OnHide", function() panel:Hide() end)

    -- Close button
    local closeBtn = CreateFrame("Button", nil, panel)
    closeBtn:SetSize(20, 20)
    closeBtn:SetPoint("TOPRIGHT", -6, -6)
    local closeTex = closeBtn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    closeTex:SetAllPoints()
    closeTex:SetText("X")
    closeTex:SetTextColor(unpack(T.textSecondary))
    closeBtn:SetScript("OnEnter", function() closeTex:SetTextColor(unpack(T.danger)) end)
    closeBtn:SetScript("OnLeave", function() closeTex:SetTextColor(unpack(T.textSecondary)) end)
    closeBtn:SetScript("OnClick", function() panel:Hide() end)

    ---------------------------------------------------------------------------
    -- Header (fixed at top): class icon + name + rank
    ---------------------------------------------------------------------------
    local classIcon = panel:CreateTexture(nil, "ARTWORK")
    classIcon:SetSize(40, 40)
    classIcon:SetPoint("TOPLEFT", 12, -12)
    classIcon:SetTexture("Interface\\GLUES\\CHARACTERCREATE\\UI-CharacterCreate-Classes")
    panel.classIcon = classIcon

    local nameText = panel:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    nameText:SetFont(nameText:GetFont(), RF.FONT_SIZES.large, "")
    nameText:SetPoint("TOPLEFT", classIcon, "TOPRIGHT", 8, -2)
    nameText:SetPoint("RIGHT", closeBtn, "LEFT", -4, 0)
    nameText:SetJustifyH("LEFT")
    panel.nameText = nameText

    local rankText = panel:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    rankText:SetFont(rankText:GetFont(), RF.FONT_SIZES.normal, "")
    rankText:SetPoint("TOPLEFT", nameText, "BOTTOMLEFT", 0, -2)
    rankText:SetTextColor(unpack(T.textSecondary))
    panel.rankText = rankText

    ---------------------------------------------------------------------------
    -- Scrollable content area (between header and bottom buttons)
    ---------------------------------------------------------------------------
    local scrollFrame = CreateFrame("ScrollFrame", nil, panel, "UIPanelScrollFrameTemplate")
    scrollFrame:SetPoint("TOPLEFT", 0, -60)
    scrollFrame:SetPoint("BOTTOMRIGHT", -24, 70)

    local content = CreateFrame("Frame", nil, scrollFrame)
    content:SetWidth(270)
    content:SetHeight(1)
    scrollFrame:SetScrollChild(content)

    local y = -6

    -- Level & Class
    panel.levelClassLabel = CreateInfoRow(content, y); y = y - 18
    -- M+ Rating
    panel.mplusLabel = CreateInfoRow(content, y); y = y - 18
    -- Achievement Points
    panel.achieveLabel = CreateInfoRow(content, y); y = y - 18
    -- Zone
    panel.zoneLabel = CreateInfoRow(content, y); y = y - 18
    -- Status
    panel.statusLabel = CreateInfoRow(content, y); y = y - 18
    -- Last Online
    panel.lastOnlineLabel = CreateInfoRow(content, y); y = y - 18
    -- Join Date
    panel.joinDateLabel = CreateInfoRow(content, y); y = y - 18
    -- Guild Reputation
    panel.guildRepLabel = CreateInfoRow(content, y); y = y - 18

    ---------------------------------------------------------------------------
    -- Professions
    ---------------------------------------------------------------------------
    CreateDividerAt(content, y - 4); y = y - 12
    CreateSectionHeader(content, "Professions:", y); y = y - 16
    panel.prof1Label = CreateInfoRow(content, y); y = y - 16
    panel.prof2Label = CreateInfoRow(content, y); y = y - 4

    ---------------------------------------------------------------------------
    -- Tags / Roles
    ---------------------------------------------------------------------------
    CreateDividerAt(content, y - 4); y = y - 12
    CreateSectionHeader(content, "Tags:", y); y = y - 16
    panel.tagsValue = CreateInfoRow(content, y)
    panel.tagsValue:SetWordWrap(true)
    y = y - 18

    ---------------------------------------------------------------------------
    -- Alt/Main
    ---------------------------------------------------------------------------
    CreateDividerAt(content, y - 4); y = y - 12
    CreateSectionHeader(content, "Alt/Main:", y); y = y - 16
    panel.altValue = CreateInfoRow(content, y)
    panel.altValue:SetWordWrap(true)
    y = y - 18

    ---------------------------------------------------------------------------
    -- Teams
    ---------------------------------------------------------------------------
    CreateDividerAt(content, y - 4); y = y - 12
    CreateSectionHeader(content, "Teams:", y); y = y - 16
    panel.teamsValue = CreateInfoRow(content, y)
    panel.teamsValue:SetWordWrap(true)
    y = y - 18

    ---------------------------------------------------------------------------
    -- Notes
    ---------------------------------------------------------------------------
    CreateDividerAt(content, y - 4); y = y - 12
    CreateSectionHeader(content, "Note:", y); y = y - 14

    local noteBtn = CreateFrame("Button", nil, content)
    noteBtn:SetPoint("TOPLEFT", 12, y)
    noteBtn:SetPoint("RIGHT", -12, 0)
    noteBtn:SetHeight(32)
    local noteValue = RF:CreateLabel(noteBtn, "", RF.FONT_SIZES.normal, "textSecondary")
    noteValue:SetPoint("TOPLEFT")
    noteValue:SetPoint("TOPRIGHT")
    noteValue:SetJustifyH("LEFT")
    noteValue:SetJustifyV("TOP")
    noteValue:SetWordWrap(true)
    noteBtn:SetScript("OnClick", function()
        local url = RF:ExtractURL(noteValue:GetText() or "")
        if url then RF:ShowCopyPopup(url) end
    end)
    panel.noteBtn = noteBtn
    panel.noteValue = noteValue
    y = y - 38

    CreateSectionHeader(content, "Officer Note:", y); y = y - 14

    local oNoteBtn = CreateFrame("Button", nil, content)
    oNoteBtn:SetPoint("TOPLEFT", 12, y)
    oNoteBtn:SetPoint("RIGHT", -12, 0)
    oNoteBtn:SetHeight(32)
    local oNoteValue = RF:CreateLabel(oNoteBtn, "", RF.FONT_SIZES.normal, "textSecondary")
    oNoteValue:SetPoint("TOPLEFT")
    oNoteValue:SetPoint("TOPRIGHT")
    oNoteValue:SetJustifyH("LEFT")
    oNoteValue:SetJustifyV("TOP")
    oNoteValue:SetWordWrap(true)
    oNoteBtn:SetScript("OnClick", function()
        local url = RF:ExtractURL(oNoteValue:GetText() or "")
        if url then RF:ShowCopyPopup(url) end
    end)
    panel.oNoteBtn = oNoteBtn
    panel.oNoteValue = oNoteValue
    y = y - 38

    ---------------------------------------------------------------------------
    -- RosterNote (multi-line editable)
    ---------------------------------------------------------------------------
    CreateDividerAt(content, y - 4); y = y - 12
    CreateSectionHeader(content, "RosterNote:", y); y = y - 16

    local extNoteScroll = CreateFrame("ScrollFrame", nil, content, "UIPanelScrollFrameTemplate")
    extNoteScroll:SetPoint("TOPLEFT", 12, y)
    extNoteScroll:SetPoint("RIGHT", -28, 0)
    extNoteScroll:SetHeight(80)

    local extNoteEB = CreateFrame("EditBox", nil, extNoteScroll)
    extNoteEB:SetWidth(230)
    extNoteEB:SetFontObject("ChatFontNormal")
    extNoteEB:SetFont(extNoteEB:GetFont(), RF.FONT_SIZES.normal, "")
    extNoteEB:SetTextColor(unpack(T.textPrimary))
    extNoteEB:SetMultiLine(true)
    extNoteEB:SetAutoFocus(false)
    extNoteEB:SetScript("OnEscapePressed", function(self) self:ClearFocus() end)
    extNoteScroll:SetScrollChild(extNoteEB)
    panel.extNoteEB = extNoteEB
    y = y - 86

    local saveExtNote = RF:CreateButton(content, "Save Note", 80, 22, "accent")
    saveExtNote:SetPoint("TOPLEFT", 12, y)
    saveExtNote:SetScript("OnClick", function()
        if currentData and RF.SetExtendedNote then
            local newText = extNoteEB:GetText()
            RF:SetExtendedNote(currentData.name, newText)
            currentData.extendedNote = newText
            RF:Print("RosterNote saved for " .. currentData.name)
            RF:RefreshRosterTab()
            saveExtNote.label:SetText("Saved!")
            C_Timer.After(1.5, function()
                saveExtNote.label:SetText("Save Note")
            end)
        end
    end)
    y = y - 30

    -- Set scroll content height
    content:SetHeight(math.abs(y) + 10)

    ---------------------------------------------------------------------------
    -- Quick Action Buttons (fixed at bottom)
    ---------------------------------------------------------------------------
    local div4 = RF:CreateDivider(panel)
    div4:SetPoint("BOTTOMLEFT", 8, 64)
    div4:SetPoint("BOTTOMRIGHT", -8, 64)

    local whisperBtn = RF:CreateButton(panel, "Whisper", 85, 24, "accent")
    whisperBtn:SetPoint("BOTTOMLEFT", 8, 36)
    whisperBtn:SetScript("OnClick", function()
        if currentData then
            ChatFrame_OpenChat("/w " .. currentData.name .. " ")
        end
    end)

    local inviteBtn = RF:CreateButton(panel, "Invite", 85, 24)
    inviteBtn:SetPoint("LEFT", whisperBtn, "RIGHT", 4, 0)
    inviteBtn:SetScript("OnClick", function()
        if currentData then
            C_PartyInfo.InviteUnit(currentData.fullName or currentData.name)
        end
    end)

    local linkAltBtn = RF:CreateButton(panel, "Link Alt", 85, 24)
    linkAltBtn:SetPoint("LEFT", inviteBtn, "RIGHT", 4, 0)
    linkAltBtn:SetScript("OnClick", function()
        if currentData then
            RF:ShowAltLinkDialog(currentData.name)
        end
    end)

    detailPanel = panel
    return panel
end

-------------------------------------------------------------------------------
-- Show Detail Panel
-------------------------------------------------------------------------------
function RF:ShowDetailPanel(data)
    if not detailPanel then
        CreateDetailPanel()
    end
    if not detailPanel then return end

    currentData = data

    -- Class icon
    local coords = CLASS_ICON_COORDS[data.classFile]
    if coords then
        detailPanel.classIcon:SetTexCoord(unpack(coords))
    end

    -- Name (class-colored)
    detailPanel.nameText:SetText(RF:GetClassColoredName(data.name, data.classFile))

    -- Rank
    detailPanel.rankText:SetText(data.rankName .. " (Rank " .. data.rankIndex .. ")")
    local rc = RF.RANK_COLORS[data.rankIndex]
    if rc then
        detailPanel.rankText:SetTextColor(rc.r, rc.g, rc.b)
    end

    -- Level & Class
    local cc = RF:GetClassColor(data.classFile)
    detailPanel.levelClassLabel:SetText(
        format("Level %d %s", data.level,
            format("|cFF%02x%02x%02x%s|r", cc.r*255, cc.g*255, cc.b*255, data.classDisplayName or ""))
    )

    -- M+ Rating
    local rating = data.mplusRating or 0
    if rating > 0 then
        local ratingColor = "FFFFFF"
        if C_ChallengeMode and C_ChallengeMode.GetDungeonScoreRarityColor then
            local c = C_ChallengeMode.GetDungeonScoreRarityColor(rating)
            if c then
                ratingColor = format("%02x%02x%02x", c.r*255, c.g*255, c.b*255)
            end
        end
        detailPanel.mplusLabel:SetText(format("M+ Rating: |cFF%s%d|r", ratingColor, rating))
    else
        detailPanel.mplusLabel:SetText("M+ Rating: None")
    end

    -- Achievement Points
    local ap = data.achievementPoints or 0
    if ap > 0 then
        detailPanel.achieveLabel:SetText(format("Achievement Points: |cFFFFD100%s|r", BreakUpLargeNumbers(ap)))
    else
        detailPanel.achieveLabel:SetText("Achievement Points: -")
    end

    -- Zone
    detailPanel.zoneLabel:SetText("Zone: " .. (data.zone ~= "" and data.zone or "Unknown"))

    -- Status
    local statusInfo = RF.STATUS[data.status]
    if statusInfo then
        local sc = statusInfo.color
        detailPanel.statusLabel:SetText(statusInfo.text)
        detailPanel.statusLabel:SetTextColor(sc.r, sc.g, sc.b)
    end

    -- Last Online
    detailPanel.lastOnlineLabel:SetText("Last Online: " .. (data.lastOnlineText or "Unknown"))

    -- Join Date
    detailPanel.joinDateLabel:SetText("Joined: " .. (data.joinDate or "Unknown"))

    -- Guild Reputation
    local repLabel = GUILD_REP_LABELS[data.repStanding] or "Unknown"
    detailPanel.guildRepLabel:SetText("Guild Rep: " .. repLabel)

    -- Professions
    local p1 = data.profession1Name
    local p2 = data.profession2Name
    if p1 and p1 ~= "" then
        detailPanel.prof1Label:SetText(format("%s (Rank %d)", p1, data.profession1Rank or 0))
    else
        detailPanel.prof1Label:SetText("None")
    end
    if p2 and p2 ~= "" then
        detailPanel.prof2Label:SetText(format("%s (Rank %d)", p2, data.profession2Rank or 0))
    else
        detailPanel.prof2Label:SetText("None")
    end

    -- Tags
    local guildDB = RF:GetGuildDB()
    local tags = guildDB and guildDB.tags and guildDB.tags[data.name]
    if tags and #tags > 0 then
        local parts = {}
        for _, t in ipairs(tags) do
            tinsert(parts, format("|cFF%s%s|r", t.color, t.label))
        end
        detailPanel.tagsValue:SetText(table.concat(parts, "  "))
    else
        detailPanel.tagsValue:SetText("None")
    end

    -- Alt/Main (show full alt chain)
    local mainName = RF:GetMainFor(data.name)
    local isMain = RF:IsMain(data.name)
    if mainName then
        local siblings = RF:GetAltsForMain(mainName)
        local others = {}
        for _, alt in ipairs(siblings) do
            if alt ~= data.name then tinsert(others, alt) end
        end
        if #others > 0 then
            detailPanel.altValue:SetText("Main: " .. mainName .. "\nAlts: " .. table.concat(others, ", "))
        else
            detailPanel.altValue:SetText("Main: " .. mainName)
        end
    elseif isMain then
        local alts = RF:GetAltsForMain(data.name)
        if #alts > 0 then
            detailPanel.altValue:SetText("Main (" .. #alts .. " alts): " .. table.concat(alts, ", "))
        else
            detailPanel.altValue:SetText("Main (no alts linked)")
        end
    else
        detailPanel.altValue:SetText(data.altMain or "None")
    end

    -- Teams
    local memberTeams = RF.GetMemberTeams and RF:GetMemberTeams(data.name) or {}
    if #memberTeams > 0 then
        local parts = {}
        for _, info in ipairs(memberTeams) do
            local roleSuffix = ""
            if info.role and info.role ~= "none" then
                local trc = RF.TEAM_ROLE_COLORS and RF.TEAM_ROLE_COLORS[info.role]
                if trc then
                    roleSuffix = format(" |cFF%02x%02x%02x(%s)|r", trc[1]*255, trc[2]*255, trc[3]*255, info.role)
                else
                    roleSuffix = " (" .. info.role .. ")"
                end
            end
            tinsert(parts, format("|cFF%02x%02x%02x%s|r%s", T.accent[1]*255, T.accent[2]*255, T.accent[3]*255, info.teamName, roleSuffix))
        end
        detailPanel.teamsValue:SetText(table.concat(parts, "\n"))
    else
        detailPanel.teamsValue:SetText("None")
    end

    -- Notes (highlight URLs in blue)
    local noteText = data.note ~= "" and data.note or "(empty)"
    local noteUrl = RF:ExtractURL(noteText)
    if noteUrl then
        detailPanel.noteValue:SetText("|cFF5BA8FF" .. noteText .. "|r")
    else
        detailPanel.noteValue:SetText(noteText)
    end

    local oNoteText = data.officerNote ~= "" and data.officerNote or "(empty)"
    local oNoteUrl = RF:ExtractURL(oNoteText)
    if oNoteUrl then
        detailPanel.oNoteValue:SetText("|cFF5BA8FF" .. oNoteText .. "|r")
    else
        detailPanel.oNoteValue:SetText(oNoteText)
    end

    -- RosterNote
    detailPanel.extNoteEB:SetText(data.extendedNote or "")

    detailPanel:Show()
end

function RF:HideDetailPanel()
    if detailPanel then
        detailPanel:Hide()
    end
end
