local addonName = ...
local LSM = LibStub("LibSharedMedia-3.0")

--------------------------------------------------
-- Forward declarations
--------------------------------------------------
local InfoFrame
local CopyFrame
local currentKey
local ShowCopyFrame

--------------------------------------------------
-- Sound registration
--------------------------------------------------
local basePath = "Interface\\AddOns\\" .. addonName .. "\\sounds\\"

local sounds = {
    "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s",
    "astral_harvest", "break", "crystalline_shockwave",
    "inverse_gravity", "out", "pools", "reverse_gravity",
    "soak", "soulfire_convergence", "soulfray_annihilation",
    "spread", "starkiller_swing", "targeted", "dot",
}

for _, sound in ipairs(sounds) do
    LSM:Register("sound", "CCS: " .. sound, basePath .. sound .. ".ogg")
end

--------------------------------------------------
-- Generic Info Frame
--------------------------------------------------
local activeFontStrings = {}

local function ClearFrame()
    for _, fs in ipairs(activeFontStrings) do
        fs:Hide()
    end
    wipe(activeFontStrings)
end

local function PopulateFrame(data)
    ClearFrame()

    local yOffset = -30
    local contentHeight = 30 -- top padding

    for _, entry in ipairs(data) do
        local fs = InfoFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        fs:SetPoint("TOPLEFT", 20, yOffset)
        fs:SetWidth(InfoFrame:GetWidth() - 40)
        fs:SetJustifyH("LEFT")
        fs:SetJustifyV("TOP")
        fs:SetWordWrap(true)

        if entry.bold then
            fs:SetFontObject("GameFontHighlightLarge")
        end

        fs:SetText(entry.text)

        local h = fs:GetStringHeight()
        yOffset = yOffset - h - 3
        contentHeight = contentHeight + h + 3

        table.insert(activeFontStrings, fs)
    end

    -- bottom padding
    contentHeight = contentHeight + 20

    -- resize the frame to fit text
    InfoFrame:SetHeight(contentHeight)
end


local function ShowInfo(data, key)
    if InCombatLockdown() then
        print("|cffff5555CCS:|r Cannot open info window during combat.")
        return
    end

    currentKey = key

    if not InfoFrame then
        InfoFrame = CreateFrame("Frame", addonName .. "_InfoFrame", UIParent, "BackdropTemplate")
        InfoFrame:SetSize(320, 750)
        InfoFrame:SetPoint("LEFT")
        InfoFrame:SetMovable(true)
        InfoFrame:EnableMouse(true)
        InfoFrame:RegisterForDrag("LeftButton")
        InfoFrame:SetScript("OnDragStart", InfoFrame.StartMoving)
        InfoFrame:SetScript("OnDragStop", InfoFrame.StopMovingOrSizing)

        InfoFrame:SetBackdrop({
            bgFile = "Interface\\Buttons\\WHITE8x8",
            edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
            tile = true,
            tileSize = 8,
            edgeSize = 12,
            insets = { left = 2, right = 2, top = 2, bottom = 2 }
        })
        InfoFrame:SetBackdropColor(0, 0, 0, 0.6)

        local close = CreateFrame("Button", nil, InfoFrame, "UIPanelCloseButton")
        close:SetPoint("TOPRIGHT", -4, -4)

        -- Profile button
        local profileBtn = CreateFrame("Button", nil, InfoFrame, "UIPanelButtonTemplate")
        profileBtn:SetSize(90, 22)
        profileBtn:SetPoint("TOPLEFT", 12, -6)
        profileBtn:SetText("Profile")

        profileBtn:SetScript("OnClick", function()
            if InCombatLockdown() then
                print("|cffff5555CCS:|r Cannot open profile window during combat.")
                return
            end
            if not currentKey then return end

            local profileVar = "CCS_Profile_" .. currentKey:gsub("^%l", string.upper)
            local profileText = _G[profileVar]

            if profileText then
                ShowCopyFrame(profileText)
            else
                print("|cffff5555CCS error:|r No profile found for '" .. currentKey .. "'")
            end
        end)
    end

    PopulateFrame(data)
    InfoFrame:Show()
end

--------------------------------------------------
-- Copy Text Frame
--------------------------------------------------
ShowCopyFrame = function(text)
    if InCombatLockdown() then
        print("|cffff5555CCS:|r Cannot open profile window during combat.")
        return
    end

    if not CopyFrame then
        CopyFrame = CreateFrame("Frame", addonName .. "_CopyFrame", UIParent, "BackdropTemplate")
        CopyFrame:SetSize(520, 240)
        CopyFrame:SetPoint("TOP")
        CopyFrame:SetFrameStrata("DIALOG") -- make sure it overlaps other frames
        CopyFrame:SetMovable(true)
        CopyFrame:EnableMouse(true)
        CopyFrame:RegisterForDrag("LeftButton")
        CopyFrame:SetScript("OnDragStart", CopyFrame.StartMoving)
        CopyFrame:SetScript("OnDragStop", CopyFrame.StopMovingOrSizing)

        CopyFrame:SetBackdrop({
            bgFile = "Interface\\Buttons\\WHITE8x8",
            edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
            tile = true,
            tileSize = 8,
            edgeSize = 12,
            insets = { left = 2, right = 2, top = 2, bottom = 2 }
        })
        CopyFrame:SetBackdropColor(0, 0, 0, 0.6)

        local close = CreateFrame("Button", nil, CopyFrame, "UIPanelCloseButton")
        close:SetPoint("TOPRIGHT", -4, -4)

        local instructions = CopyFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        instructions:SetPoint("TOP", 0, -20)
        instructions:SetWidth(480)
        instructions:SetJustifyH("CENTER")
        instructions:SetWordWrap(true)
        instructions:SetText(
            "Copy this text and paste it into the import box under\n" ..
            "BigWigs - Raid Bosses - Manaforge Omega - Share"
        )

        local editBox = CreateFrame("EditBox", nil, CopyFrame)
        editBox:SetMultiLine(true)
        editBox:SetFontObject("GameFontHighlight")
        editBox:SetWidth(480)
        editBox:SetHeight(120)
        editBox:SetPoint("TOP", instructions, "BOTTOM", 0, -16)
        editBox:SetAutoFocus(false)            -- stop auto-focusing
        editBox:SetCursorPosition(0)           -- move cursor to start
        editBox:HighlightText()                -- highlight text on open

        -- only highlight text the first time the box opens
        editBox:SetScript("OnEscapePressed", function(self)
            self:ClearFocus()
        end)

        -- prevent highlighting or reselecting text on keypress after initial open
        editBox:SetScript("OnTextChanged", function(self)
            -- do nothing; user edits not allowed
        end)

        CopyFrame.editBox = editBox
    end

    CopyFrame.editBox:SetText(text)
    CopyFrame.editBox:HighlightText() -- initial highlight
    CopyFrame:Raise()       -- ensure it visually overlaps the info frame
    CopyFrame:Show()
end


--------------------------------------------------
-- Slash command handler
--------------------------------------------------
SLASH_CCS1 = "/ccs"

SlashCmdList["CCS"] = function(msg)
    local cmd, arg = msg:match("^(%S+)%s*(.*)$")
    cmd = cmd and cmd:lower() or ""

    if cmd == "" then
        print("|cffff5555CCS available commands:|r /ccs manaforge OR /ccs profile manaforge")
        return
    end

    -- /ccs profile <name>
    if cmd == "profile" then
        local key = arg:lower()
        if key == "" then
            print("|cffff5555CCS usage:|r /ccs profile <name>")
            return
        end

        local profileVar = "CCS_Profile_" .. key:gsub("^%l", string.upper)
        local profileText = _G[profileVar]

        if not profileText then
            print("|cffff5555CCS error:|r No profile found for '" .. key .. "'")
            return
        end

        ShowCopyFrame(profileText)
        return
    end

    -- /ccs <name>
    local tableName = "CCS_" .. cmd:gsub("^%l", string.upper)
    local data = _G[tableName]

    if not data then
        print("|cffff5555CCS error:|r No data file found for '" .. cmd .. "'")
        return
    end

    ShowInfo(data, cmd)
end
