-- Cowmera_Lura.lua
-- L'ura sequence helper. Drop this file into Interface/AddOns/Cowmera/ and add it to Cowmera.toc.
-- Works in combat because it only uses normal UI buttons/textures and addon chat messages.

local ADDON_NAME = ...
local PREFIX = "COWMERA_LURA"

CowmeraDB = CowmeraDB or {}
CowmeraDB.lura = CowmeraDB.lura or {}

local LURA = _G.CowmeraLura or {}
_G.CowmeraLura = LURA

local ICONS = {
    { id = 1, key = "triangle", label = "Triangle", warningLabel = "Triangle", raidIcon = "{rt4}", texture = "Interface\\AddOns\\Cowmera\\Media\\Lura\\triangle.tga" },
    { id = 2, key = "hammer",   label = "Hammer",   warningLabel = "Star",     raidIcon = "{rt1}", texture = "Interface\\AddOns\\Cowmera\\Media\\Lura\\hammer.tga"   },
    { id = 3, key = "diamond",  label = "Diamond",  warningLabel = "Diamond",  raidIcon = "{rt3}", texture = "Interface\\AddOns\\Cowmera\\Media\\Lura\\diamond.tga"  },
    { id = 4, key = "cross",    label = "Cross",    warningLabel = "X",        raidIcon = "{rt7}", texture = "Interface\\AddOns\\Cowmera\\Media\\Lura\\cross.tga"    },
    { id = 5, key = "spiral",   label = "Spiral",   warningLabel = "Circle",   raidIcon = "{rt2}", texture = "Interface\\AddOns\\Cowmera\\Media\\Lura\\spiral.tga"   },
}

local order = {}
local panels = {}
local floatingFrame

local function LuraDB()
    CowmeraDB = CowmeraDB or {}
    CowmeraDB.lura = CowmeraDB.lura or {}
    return CowmeraDB.lura
end

local function GetBackdropAlpha()
    local db = LuraDB()
    local a = tonumber(db.backgroundAlpha)
    if not a then
        a = 0.96
        db.backgroundAlpha = a
    end
    if a < 0.15 then a = 0.15 end
    if a > 1 then a = 1 end
    return a
end

local function SetBackdropAlpha(frame, alpha)
    if not frame or not frame.SetBackdropColor then return end
    local r, g, b = frame._cowmeraLuraBackdropR or 0.04, frame._cowmeraLuraBackdropG or 0.035, frame._cowmeraLuraBackdropB or 0.12
    frame:SetBackdropColor(r, g, b, alpha)
end

local function UpdatePanelBackdropAlpha(panel)
    if not panel then return end
    local a = GetBackdropAlpha()
    SetBackdropAlpha(panel.helperFrame, a)
    SetBackdropAlpha(panel.sequenceFrame, a)
    if panel.alphaValueText then
        panel.alphaValueText:SetText(string.format("%d%%", math.floor((a * 100) + 0.5)))
    end
    if panel.alphaSlider and not panel.alphaSlider._cowmeraUpdating then
        panel.alphaSlider._cowmeraUpdating = true
        panel.alphaSlider:SetValue(a)
        panel.alphaSlider._cowmeraUpdating = false
    end
end

local function UpdateAllBackdropAlpha()
    for _, panel in pairs(panels) do
        UpdatePanelBackdropAlpha(panel)
    end
end

local function IsLeadOrAssist()
    if not IsInRaid() then
        return false
    end
    return UnitIsGroupLeader("player") or UnitIsGroupAssistant("player")
end

local function GetGroupChannel()
    if IsInGroup(LE_PARTY_CATEGORY_INSTANCE) then return "INSTANCE_CHAT" end
    if IsInRaid() then return "RAID" end
    if IsInGroup() then return "PARTY" end
    return nil
end

local function GetIconById(id)
    id = tonumber(id)
    for _, icon in ipairs(ICONS) do
        if icon.id == id then return icon end
    end
end

local function SetButtonEnabledVisual(btn, enabled)
    if not btn then return end
    if enabled then
        btn:Enable()
        if btn.icon then btn.icon:SetDesaturated(false); btn.icon:SetAlpha(1) end
        if btn.border then btn.border:SetAlpha(0.9) end
    else
        btn:Disable()
        if btn.icon then btn.icon:SetDesaturated(true); btn.icon:SetAlpha(0.45) end
        if btn.border then btn.border:SetAlpha(0.25) end
    end
end

local function WipeSequenceSlots(panel)
    if not panel or not panel.sequenceSlots then return end
    for i = 1, 5 do
        local slot = panel.sequenceSlots[i]
        if slot then
            slot.texture:SetTexture(nil)
            slot.number:SetText("")
            if slot.label then slot.label:SetText("") end
        end
    end
end

local CowmeraLuraApplyClickThrough

local function RefreshOnePanel(panel)
    if not panel or not panel.sequenceFrame then return end
    WipeSequenceSlots(panel)

    local positions = {
        [1] = { x =  72, y =  18 }, -- upper right
        [2] = { x =  60, y = -48 }, -- lower right
        [3] = { x =   0, y = -86 }, -- bottom center
        [4] = { x = -60, y = -48 }, -- lower left
        [5] = { x = -72, y =  18 }, -- upper left
    }

    for seqIndex, iconId in ipairs(order) do
        local icon = GetIconById(iconId)
        local slot = panel.sequenceSlots[seqIndex]
        local pos = positions[seqIndex]
        if icon and slot and pos then
            slot:ClearAllPoints()
            slot:SetPoint("CENTER", panel.sequenceFrame, "CENTER", pos.x, pos.y)
            slot.texture:SetTexture(icon.texture)
            slot.number:SetText(tostring(seqIndex))
            if slot.label then
                slot.label:SetText(string.upper(icon.label))
            end
        end
    end

    local canEdit = IsLeadOrAssist()
    local inputHidden = not not LuraDB().inputHidden
    local showHelper = canEdit and not inputHidden

    -- Only raid lead / raid assistants should be able to show the Memory Helper input box.
    -- Everyone else still sees the L'ura Sequence box.
    if panel.helperFrame then
        panel.helperFrame:SetShown(showHelper)
    end
    if panel.inputMoveBtn then
        panel.inputMoveBtn:SetShown(showHelper)
        panel.inputMoveBtn:SetEnabled(showHelper)
    end
    if panel.inputToggleBtn then
        panel.inputToggleBtn:SetShown(canEdit)
        panel.inputToggleBtn:SetText(inputHidden and "Show Input" or "Hide Input")
    end
    if panel.sequenceMoveBtn then
        panel.sequenceMoveBtn:SetShown(true)
        panel.sequenceMoveBtn:SetEnabled(not (InCombatLockdown and InCombatLockdown()))
    end

    if panel.statusText then
        if canEdit then
            panel.statusText:SetText("Raid lead / assist input enabled")
            panel.statusText:SetTextColor(0.35, 1, 0.35, 1)
        else
            panel.statusText:SetText("View only: raid lead or assistants can set L'ura")
            panel.statusText:SetTextColor(1, 0.35, 0.35, 1)
        end
    end

    if panel.inputButtons then
        for _, btn in ipairs(panel.inputButtons) do
            SetButtonEnabledVisual(btn, canEdit)
        end
    end
    if panel.sendBtn then SetButtonEnabledVisual(panel.sendBtn, canEdit) end
    if panel.clearBtn then SetButtonEnabledVisual(panel.clearBtn, canEdit) end

    if panel.enableBtn and panel.disableBtn then
        local enabled = not not LuraDB().enabled
        panel.enableBtn:SetEnabled(not enabled)
        panel.disableBtn:SetEnabled(enabled)
        if panel.persistText then
            if enabled then
                panel.persistText:SetText("Enabled: LURA stays on screen when Cowmera is closed")
                panel.persistText:SetTextColor(0.35, 1, 0.35, 1)
            else
                panel.persistText:SetText("Disabled: LURA only shows inside this tab")
                panel.persistText:SetTextColor(1, 0.8, 0.25, 1)
            end
        end
    end
    if CowmeraLuraApplyClickThrough then
        CowmeraLuraApplyClickThrough(panel)
    end
end

local function RefreshAllPanels()
    for frame, panel in pairs(panels) do
        if frame and panel then
            RefreshOnePanel(panel)
        end
    end
end

local function SaveSequence()
    LuraDB().sequence = table.concat(order, ",")
end

local function SetSequenceFromCSV(csv)
    wipe(order)
    for token in string.gmatch(csv or "", "[^,]+") do
        local id = tonumber(token)
        if GetIconById(id) and #order < 5 then
            table.insert(order, id)
        end
    end
    SaveSequence()
    RefreshAllPanels()
end


local function BuildRaidWarningText()
    if not order or #order == 0 then
        return "none"
    end

    local parts = {}
    for i = 1, #order do
        local icon = GetIconById(order[i])
        if icon then
            -- Raid target tags render as WoW raid icons in chat/raid warning.
            -- Use the selected order and wrap each label with its raid icon.
            -- Example: {rt1}Hammer{rt1}~{rt3}Diamond{rt3}
            table.insert(parts, icon.raidIcon .. icon.label .. icon.raidIcon)
        end
    end
    return table.concat(parts, "~")
end

local function SendRaidWarningSequence()
    if not IsLeadOrAssist() then return end
    if not IsInRaid() then return end
    SendChatMessage(BuildRaidWarningText(), "RAID_WARNING")
end

local function SendSequence()
    if not IsLeadOrAssist() then
        PlaySound(1537084, "Master")
        RefreshAllPanels()
        return
    end
    local channel = GetGroupChannel()
    if not channel then
        RefreshAllPanels()
        return
    end
    C_ChatInfo.SendAddonMessage(PREFIX, "SEQ|" .. table.concat(order, ","), channel)
    SendRaidWarningSequence()
end

local function ClearSequence(shouldSend)
    if not IsLeadOrAssist() then
        PlaySound(1537084, "Master")
        RefreshAllPanels()
        return
    end
    wipe(order)
    SaveSequence()
    RefreshAllPanels()
    if shouldSend then
        -- Broadcast the cleared sequence to Cowmera users only.
        -- Do not send a Raid Warning when clearing.
        local channel = GetGroupChannel()
        if channel then
            C_ChatInfo.SendAddonMessage(PREFIX, "SEQ|", channel)
        end
    end
end

local function AddIconToSequence(iconId)
    if not IsLeadOrAssist() then
        PlaySound(1537084, "Master")
        return
    end
    if #order >= 5 then
        PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON, "Master")
        return
    end
    table.insert(order, iconId)
    SaveSequence()
    RefreshAllPanels()
end

local function MakeBackdrop(frame, r, g, b, a)
    frame:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
        tile = true, tileSize = 16,
        insets = { left = 4, right = 4, top = 4, bottom = 4 },
    })
    frame._cowmeraLuraBackdropR = r or 0.05
    frame._cowmeraLuraBackdropG = g or 0.04
    frame._cowmeraLuraBackdropB = b or 0.16
    frame:SetBackdropColor(frame._cowmeraLuraBackdropR, frame._cowmeraLuraBackdropG, frame._cowmeraLuraBackdropB, GetBackdropAlpha())
end

local function MakeTextButton(parent, text, width, height)
    local btn = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
    btn:SetSize(width, height)
    btn:SetText(text)
    return btn
end


local function CowmeraLuraBackgroundClickThrough(frame)
    if not frame then return end
    if frame.EnableMouse then frame:EnableMouse(false) end
    if frame.SetMouseClickEnabled then pcall(frame.SetMouseClickEnabled, frame, false) end
    if frame.SetMouseMotionEnabled then pcall(frame.SetMouseMotionEnabled, frame, false) end
end

local function CowmeraLuraButtonLeftOnly(btn)
    if not btn then return end
    if btn.EnableMouse then btn:EnableMouse(true) end
    if btn.RegisterForClicks then pcall(btn.RegisterForClicks, btn, "LeftButtonUp") end
end

local function CowmeraLuraSaveChildPosition(child, keyPrefix)
    if not child or not keyPrefix then return end
    local point, _, relPoint, x, y = child:GetPoint(1)
    local db = LuraDB()
    db[keyPrefix .. "Point"] = point
    db[keyPrefix .. "RelPoint"] = relPoint
    db[keyPrefix .. "X"] = x
    db[keyPrefix .. "Y"] = y
end

local function CowmeraLuraRestoreChildPosition(child, keyPrefix, defaultPoint, defaultRelPoint, defaultX, defaultY)
    if not child or not keyPrefix then return end
    local db = LuraDB()
    child:ClearAllPoints()
    child:SetPoint(
        db[keyPrefix .. "Point"] or defaultPoint,
        child:GetParent(),
        db[keyPrefix .. "RelPoint"] or defaultRelPoint,
        db[keyPrefix .. "X"] or defaultX,
        db[keyPrefix .. "Y"] or defaultY
    )
end

local function CowmeraLuraMakeChildMoveButton(btn, child, keyPrefix)
    if not btn or not child or not keyPrefix then return end
    CowmeraLuraButtonLeftOnly(btn)

    btn:SetScript("OnMouseDown", function(self, button)
        if button ~= "LeftButton" then return end
        if InCombatLockdown and InCombatLockdown() then return end
        if child.SetMovable then child:SetMovable(true) end
        if child.EnableMouse then child:EnableMouse(true) end
        child:StartMoving()
        self._cowmeraMovingChild = true
    end)

    btn:SetScript("OnMouseUp", function(self, button)
        if button ~= "LeftButton" then return end
        if self._cowmeraMovingChild then
            child:StopMovingOrSizing()
            CowmeraLuraSaveChildPosition(child, keyPrefix)
            CowmeraLuraBackgroundClickThrough(child)
        end
        self._cowmeraMovingChild = false
    end)

    btn:SetScript("OnHide", function(self)
        if self._cowmeraMovingChild then
            child:StopMovingOrSizing()
            CowmeraLuraSaveChildPosition(child, keyPrefix)
            CowmeraLuraBackgroundClickThrough(child)
        end
        self._cowmeraMovingChild = false
    end)
end

CowmeraLuraApplyClickThrough = function(panel)
    if not panel then return end

    -- Background/panel areas stay mouse-disabled so right-click camera passthrough works.
    CowmeraLuraBackgroundClickThrough(panel.frame)
    CowmeraLuraBackgroundClickThrough(panel.helperFrame)
    CowmeraLuraBackgroundClickThrough(panel.sequenceFrame)

    if panel.sequenceSlots then
        for _, slot in pairs(panel.sequenceSlots) do
            CowmeraLuraBackgroundClickThrough(slot)
        end
    end

    -- Only actual controls are clickable.
    if panel.inputButtons then
        for _, btn in ipairs(panel.inputButtons) do
            CowmeraLuraButtonLeftOnly(btn)
        end
    end
    CowmeraLuraButtonLeftOnly(panel.sendBtn)
    CowmeraLuraButtonLeftOnly(panel.clearBtn)
    CowmeraLuraButtonLeftOnly(panel.inputToggleBtn)
    CowmeraLuraButtonLeftOnly(panel.inputMoveBtn)
    CowmeraLuraButtonLeftOnly(panel.sequenceMoveBtn)
    CowmeraLuraButtonLeftOnly(panel.enableBtn)
    CowmeraLuraButtonLeftOnly(panel.disableBtn)
    CowmeraLuraButtonLeftOnly(panel.alphaSlider)
end

local function MakeIconButton(parent, icon)
    local btn = CreateFrame("Button", nil, parent)
    btn:SetSize(52, 52)
    btn.icon = btn:CreateTexture(nil, "ARTWORK")
    btn.icon:SetAllPoints()
    btn.icon:SetTexture(icon.texture)
    btn.border = btn:CreateTexture(nil, "OVERLAY")
    btn.border:SetTexture("Interface\\Buttons\\UI-ActionButton-Border")
    btn.border:SetBlendMode("ADD")
    btn.border:SetAllPoints()
    btn.border:SetVertexColor(0.65, 0.1, 1, 0.9)
    btn:SetScript("OnClick", function() AddIconToSequence(icon.id) end)
    btn:SetScript("OnEnter", function(self)
        GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
        GameTooltip:SetText(icon.label)
        if not IsLeadOrAssist() then
            GameTooltip:AddLine("Only raid lead or raid assistants can input.", 1, 0.25, 0.25, true)
        else
            GameTooltip:AddLine("Click to add this icon to the sequence.", 0.8, 0.8, 0.8, true)
        end
        GameTooltip:Show()
    end)
    btn:SetScript("OnLeave", GameTooltip_Hide)
    return btn
end

local function CreateLuraUI(parent, isFloating)
    local frame = CreateFrame("Frame", isFloating and "CowmeraLuraFloatingPanel" or nil, parent or UIParent, "BackdropTemplate")
    frame:SetSize(810, isFloating and 360 or 330)

    if isFloating then
        frame:SetPoint("CENTER", UIParent, "CENTER", 0, 80)
        frame:EnableMouse(false)
        frame:SetMovable(true)
    else
        frame:SetAllPoints(parent)
    end

    local panel = {
        frame = frame,
        inputButtons = {},
        sequenceSlots = {},
        isFloating = isFloating,
    }
    panels[frame] = panel

    if isFloating then
    else
        -- The Cowmera tab only needs controls for showing/hiding the persistent LURA window.
        -- The memory helper, icon input buttons, send/clear buttons, and sequence display live only in the persistent frame.
        frame:SetSize(810, 70)

        local enableBtn = MakeTextButton(frame, "Enable", 110, 28)
        enableBtn:SetPoint("TOPLEFT", frame, "TOPLEFT", 12, -12)
        enableBtn:SetScript("OnClick", function() LURA.EnablePersistent() end)
        panel.enableBtn = enableBtn

        local disableBtn = MakeTextButton(frame, "Disable", 110, 28)
        disableBtn:SetPoint("LEFT", enableBtn, "RIGHT", 10, 0)
        disableBtn:SetScript("OnClick", function() LURA.DisablePersistent() end)
        panel.disableBtn = disableBtn

        local alphaLabel = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        alphaLabel:SetPoint("LEFT", disableBtn, "RIGHT", 24, 0)
        alphaLabel:SetText("Background Transparency")

        local alphaValueText = frame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
        alphaValueText:SetPoint("LEFT", alphaLabel, "RIGHT", 8, 0)
        panel.alphaValueText = alphaValueText

        local alphaSlider = CreateFrame("Slider", nil, frame, "OptionsSliderTemplate")
        alphaSlider:SetSize(180, 16)
        alphaSlider:SetPoint("LEFT", alphaValueText, "RIGHT", 18, 0)
        alphaSlider:SetMinMaxValues(0.15, 1.0)
        alphaSlider:SetValueStep(0.05)
        alphaSlider:SetObeyStepOnDrag(true)
        alphaSlider:SetValue(GetBackdropAlpha())
        alphaSlider.Low:SetText("Clear")
        alphaSlider.High:SetText("Solid")
        alphaSlider.Text:SetText("")
        alphaSlider:SetScript("OnValueChanged", function(self, value)
            if self._cowmeraUpdating then return end
            value = tonumber(value) or 0.96
            value = math.floor((value / 0.05) + 0.5) * 0.05
            if value < 0.15 then value = 0.15 end
            if value > 1 then value = 1 end
            LuraDB().backgroundAlpha = value
            if panel.alphaValueText then
                panel.alphaValueText:SetText(string.format("%d%%", math.floor((value * 100) + 0.5)))
            end
            UpdateAllBackdropAlpha()
        end)
        panel.alphaSlider = alphaSlider
        CowmeraLuraButtonLeftOnly(alphaSlider)

        RefreshOnePanel(panel)
        return frame
    end

    local topOffset = -12

    local helperFrame = CreateFrame("Frame", nil, frame, "BackdropTemplate")
    CowmeraLuraBackgroundClickThrough(helperFrame)
    helperFrame:SetSize(455, 190)
    CowmeraLuraRestoreChildPosition(helperFrame, "helper", "TOPLEFT", "TOPLEFT", 8, topOffset)
    helperFrame:SetMovable(true)
    MakeBackdrop(helperFrame, 0.04, 0.035, 0.12, 0.96)
    panel.helperFrame = helperFrame

    local title = helperFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOP", 0, -18)
    title:SetText("L'ura Memory Helper")
    title:SetTextColor(1, 0.82, 0, 1)

    local inputMoveBtn = MakeTextButton(helperFrame, "~~~", 42, 22)
    inputMoveBtn:SetPoint("TOPRIGHT", helperFrame, "TOPRIGHT", -12, -10)
    CowmeraLuraMakeChildMoveButton(inputMoveBtn, helperFrame, "helper")
    panel.inputMoveBtn = inputMoveBtn

    local startX = 62
    for i, icon in ipairs(ICONS) do
        local btn = MakeIconButton(helperFrame, icon)
        btn:SetPoint("TOPLEFT", helperFrame, "TOPLEFT", startX + ((i - 1) * 84), -58)
        panel.inputButtons[i] = btn

        local lbl = helperFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
        lbl:SetPoint("TOP", btn, "BOTTOM", 0, -3)
        lbl:SetText(icon.label)
        lbl:SetTextColor(1, 0.9, 0, 1)
    end

    local sendBtn = MakeTextButton(helperFrame, "Send", 110, 28)
    sendBtn:SetPoint("BOTTOM", helperFrame, "BOTTOM", -75, 18)
    sendBtn:SetScript("OnClick", SendSequence)
    panel.sendBtn = sendBtn

    local clearBtn = MakeTextButton(helperFrame, "Clear", 110, 28)
    clearBtn:SetPoint("BOTTOM", helperFrame, "BOTTOM", 75, 18)
    clearBtn:SetScript("OnClick", function() ClearSequence(true) end)
    panel.clearBtn = clearBtn

    local statusText = helperFrame:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    statusText:SetPoint("BOTTOM", helperFrame, "BOTTOM", 0, 2)
    statusText:SetText("")
    panel.statusText = statusText

    local sequenceFrame = CreateFrame("Frame", nil, frame, "BackdropTemplate")
    CowmeraLuraBackgroundClickThrough(sequenceFrame)
    sequenceFrame:SetSize(330, 330)
    CowmeraLuraRestoreChildPosition(sequenceFrame, "sequence", "TOPLEFT", "TOPLEFT", 481, topOffset)
    sequenceFrame:SetMovable(true)
    MakeBackdrop(sequenceFrame, 0.02, 0.015, 0.08, 0.96)
    panel.sequenceFrame = sequenceFrame

    local st = sequenceFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    st:SetPoint("TOP", 0, -12)
    st:SetText("L'ura Sequence")
    st:SetTextColor(0.95, 0.9, 1, 1)

    local sequenceMoveBtn = MakeTextButton(sequenceFrame, "~~~", 42, 22)
    sequenceMoveBtn:SetPoint("TOPLEFT", sequenceFrame, "TOPLEFT", 12, -10)
    CowmeraLuraMakeChildMoveButton(sequenceMoveBtn, sequenceFrame, "sequence")
    panel.sequenceMoveBtn = sequenceMoveBtn

    local inputToggleBtn = MakeTextButton(sequenceFrame, "Hide Input", 86, 22)
    inputToggleBtn:SetPoint("TOPRIGHT", sequenceFrame, "TOPRIGHT", -12, -10)
    inputToggleBtn:SetScript("OnClick", function()
        if not IsLeadOrAssist() then
            PlaySound(1537084, "Master")
            return
        end
        LuraDB().inputHidden = not not not LuraDB().inputHidden
        RefreshAllPanels()
    end)
    CowmeraLuraButtonLeftOnly(inputToggleBtn)
    panel.inputToggleBtn = inputToggleBtn

    local bossArt = sequenceFrame:CreateTexture(nil, "ARTWORK")
    bossArt:SetTexture("Interface\\AddOns\\Cowmera\\Media\\Lura\\boss.tga")
    bossArt:SetSize(220, 270)
    bossArt:SetPoint("CENTER", sequenceFrame, "CENTER", 0, -18)
    bossArt:SetAlpha(0.55)

    local boss = sequenceFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalHuge")
    boss:SetPoint("CENTER", 0, 2)
    boss:SetText("BOSS")
    boss:SetTextColor(1, 0, 0, 1)

    local tanksText = sequenceFrame:CreateFontString(nil, "OVERLAY")
    tanksText:SetFont(STANDARD_TEXT_FONT, 11, "")
    tanksText:SetPoint("CENTER", sequenceFrame, "CENTER", 0, 72)
    tanksText:SetText("TANKS")
    tanksText:SetTextColor(0.2, 0.7, 1.0, 1)
    tanksText:SetShadowColor(0.2, 0.7, 1.0, 0.9)
    tanksText:SetShadowOffset(1, -1)
    panel.tanksText = tanksText

    for i = 1, 5 do
        local slot = CreateFrame("Frame", nil, sequenceFrame)
        slot:SetSize(60, 60)
        slot.texture = slot:CreateTexture(nil, "ARTWORK")
        slot.texture:SetSize(56, 56)
        slot.texture:SetPoint("CENTER")
        slot.number = slot:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        slot.number:SetPoint("BOTTOM", slot, "BOTTOM", 0, -12)
        slot.number:SetTextColor(1, 0.9, 0, 1)

        slot.label = slot:CreateFontString(nil, "OVERLAY")
        slot.label:SetFont(STANDARD_TEXT_FONT, 11, "")
        slot.label:SetPoint("BOTTOM", slot, "TOP", 0, -10)
        slot.label:SetTextColor(1, 0, 0, 1)
        slot.label:SetShadowColor(1.0, 0.0, 0.0, 0.9)
        slot.label:SetShadowOffset(1, -1)

        panel.sequenceSlots[i] = slot
    end

    local lockIcon = sequenceFrame:CreateTexture(nil, "ARTWORK")
    lockIcon:SetSize(56, 56)
    lockIcon:SetPoint("CENTER", sequenceFrame, "CENTER", 0, 82)
    lockIcon:SetTexture("Interface\\AddOns\\Cowmera\\Media\\Lura\\tank.tga")

    CowmeraLuraApplyClickThrough(panel)
    UpdatePanelBackdropAlpha(panel)
    RefreshOnePanel(panel)
    return frame
end

local function EnsureFloatingFrame()
    if floatingFrame then return floatingFrame end
    floatingFrame = CreateLuraUI(UIParent, true)
    local db = LuraDB()
    if db.point and db.x and db.y then
        floatingFrame:ClearAllPoints()
        floatingFrame:SetPoint(db.point, UIParent, db.relPoint or db.point, db.x, db.y)
    end
    floatingFrame:Hide()
    return floatingFrame
end

function LURA.EnablePersistent()
    LuraDB().enabled = true
    local frame = EnsureFloatingFrame()
    frame:Show()
    RefreshAllPanels()
end

function LURA.DisablePersistent()
    LuraDB().enabled = false
    if floatingFrame then floatingFrame:Hide() end
    RefreshAllPanels()
end

function LURA.Show(parent)
    if parent then
        if not parent.CowmeraLuraEmbeddedFrame then
            parent.CowmeraLuraEmbeddedFrame = CreateLuraUI(parent, false)
        end
        parent.CowmeraLuraEmbeddedFrame:Show()
        RefreshAllPanels()
        return parent.CowmeraLuraEmbeddedFrame
    end

    local frame = EnsureFloatingFrame()
    frame:Show()
    RefreshAllPanels()
    return frame
end

function LURA.Hide()
    if floatingFrame then floatingFrame:Hide() end
end

function LURA.Toggle()
    local frame = EnsureFloatingFrame()
    if frame:IsShown() then
        LURA.DisablePersistent()
    else
        LURA.EnablePersistent()
    end
end

-- Compatibility helper for Cowmera tab systems.
function Cowmera_CreateLuraPanel(parent)
    return LURA.Show(parent)
end

local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("PLAYER_LOGIN")
eventFrame:RegisterEvent("GROUP_ROSTER_UPDATE")
eventFrame:RegisterEvent("CHAT_MSG_ADDON")
eventFrame:SetScript("OnEvent", function(_, event, ...)
    if event == "PLAYER_LOGIN" then
        C_ChatInfo.RegisterAddonMessagePrefix(PREFIX)
        SLASH_COWMERALURA1 = "/cowmeralura"
        SlashCmdList.COWMERALURA = function() LURA.Toggle() end
        if LuraDB().sequence and LuraDB().sequence ~= "" then
            SetSequenceFromCSV(LuraDB().sequence)
        else
            RefreshAllPanels()
        end
        if LuraDB().enabled then
            LURA.EnablePersistent()
        end
    elseif event == "GROUP_ROSTER_UPDATE" then
        RefreshAllPanels()
    elseif event == "CHAT_MSG_ADDON" then
        local prefix, msg = ...
        if prefix ~= PREFIX or type(msg) ~= "string" then return end
        local command, payload = strsplit("|", msg, 2)
        if command == "SEQ" then
            SetSequenceFromCSV(payload or "")
        end
    end
end)
