local _, addon = ...
local HLY = addon.HLY

local MARK_NAMES = {
    [0] = "Kein Mark",
    [1] = "Stern",
    [2] = "Kreis",
    [3] = "Diamant",
    [4] = "Dreieck",
    [5] = "Mond",
    [6] = "Quadrat",
    [7] = "Kreuz",
    [8] = "Totenkopf",
}

local MACRO_NAME = "HLYmarkerTank"
local MACRO_ICON = "INV_MISC_QUESTIONMARK"
local MACRO_PLACEHOLDER = "/run print('HLYqol: Kein Tank in normaler Party gefunden.')"

local function GetMarkerIconText(mark)
    if not mark or mark < 1 or mark > 8 then return "" end
    return string.format("|TInterface\\TargetingFrame\\UI-RaidTargetingIcon_%d:0|t ", mark)
end

function HLY:GetMarkerDisplayText(mark)
    return GetMarkerIconText(mark) .. (MARK_NAMES[mark] or tostring(mark))
end

local function IsInPartyGroup()
    return IsInGroup() and not IsInRaid()
end

local function FindTankUnit()
    if UnitExists("player") and UnitGroupRolesAssigned("player") == "TANK" then
        return "player"
    end
    for i = 1, GetNumSubgroupMembers() do
        local unit = "party" .. i
        if UnitExists(unit) and UnitGroupRolesAssigned(unit) == "TANK" then
            return unit
        end
    end
    return nil
end

local function CanPlayerSetRaidIcon()
    if IsInRaid() then
        return UnitIsGroupLeader("player") or UnitIsGroupAssistant("player")
    end
    return IsInGroup()
end

function HLY:BuildMarkerMacroText()
    local db = self.db and self.db.marker
    if not db or not db.enabled or db.mark == 0 then return nil end
    if not IsInPartyGroup() then return nil end
    local tankUnit = FindTankUnit()
    if not tankUnit or not UnitIsPlayer(tankUnit) then return nil end
    return string.format("/target %s\n/tm %d\n/targetlasttarget", tankUnit, db.mark)
end

local function EnsureMarkerMacro(self)
    local macroIndex = GetMacroIndexByName(MACRO_NAME)
    if macroIndex and macroIndex > 0 then return macroIndex end
    local numGlobal, numChar = GetNumMacros()
    local body = self:BuildMarkerMacroText() or MACRO_PLACEHOLDER
    if (numGlobal or 0) < (MAX_ACCOUNT_MACROS or 120) then
        return CreateMacro(MACRO_NAME, MACRO_ICON, body, false)
    end
    if (numChar or 0) < (MAX_CHARACTER_MACROS or 18) then
        return CreateMacro(MACRO_NAME, MACRO_ICON, body, true)
    end
    return nil
end

function HLY:UpdateMarkerMacroNow()
    local db = self.db and self.db.marker
    if not db or not db.enabled then return end
    local macroIndex = EnsureMarkerMacro(self)
    if not macroIndex or macroIndex <= 0 then return end
    EditMacro(macroIndex, MACRO_NAME, MACRO_ICON, self:BuildMarkerMacroText() or MACRO_PLACEHOLDER)
    self.markerPendingMacroUpdate = false
end

function HLY:QueueMarkerMacroUpdate()
    if InCombatLockdown and InCombatLockdown() then
        self.markerPendingMacroUpdate = true
        return
    end
    self:UpdateMarkerMacroNow()
end

function HLY:BuildMarkerReminderFrame()
    if self.markerReminderFrame then return end
    local db = self.db and self.db.marker
    if not db then return end

    -- Plain frame: owns position, size, visibility and text.
    local holder = CreateFrame("Frame", "HLYqolMarkerReminderHolder", UIParent)
    holder:SetFrameStrata("MEDIUM")
    holder:SetClampedToScreen(true)
    holder:SetSize(280, 40)
    holder:SetPoint("CENTER", UIParent, "CENTER", db.reminderX or 0, db.reminderY or 140)
    holder:Hide()

    local text = holder:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    text:SetPoint("CENTER")
    text:SetTextColor(1, 0.82, 0.1)

    self.markerReminderFrame = holder
    self.markerReminderText = text
end

function HLY:ShouldShowMarkerReminder()
    local db = self.db and self.db.marker
    if not db or not db.enabled then return false end
    if not IsInPartyGroup() or not CanPlayerSetRaidIcon() then return false end
    if db.mark == 0 then return false end
    local tankUnit = FindTankUnit()
    if not tankUnit or not UnitIsPlayer(tankUnit) then return false end
    return GetRaidTargetIndex(tankUnit) == nil
end

function HLY:RefreshMarkerReminder()
    self:BuildMarkerReminderFrame()
    local db = self.db and self.db.marker
    local f = self.markerReminderFrame
    if not f then return end

    if db then
        local text = self.markerReminderText
        if text then
            text:SetText(GetMarkerIconText(db.mark) .. "Tank nicht gemarkt!")
            local fontPath, _, flags = text:GetFont()
            if fontPath then
                local size = db.reminderFontSize
                if size < 10 then size = 10 elseif size > 36 then size = 36 end
                text:SetFont(fontPath, size, flags)
            end
        end
        f:ClearAllPoints()
        f:SetPoint("CENTER", UIParent, "CENTER", db.reminderX, db.reminderY)
    end

    local showForPreview = self.markerReminderPreviewActive and db and db.enabled
    if showForPreview or self:ShouldShowMarkerReminder() then f:Show() else f:Hide() end
end

function HLY:ShowMarkerReminderPreview()
    if self.markerReminderPreviewActive then return end
    self.markerReminderPreviewActive = true
    self:RefreshMarkerReminder()
end

function HLY:HideMarkerReminderPreview()
    if not self.markerReminderPreviewActive then return end
    self.markerReminderPreviewActive = false
    self:RefreshMarkerReminder()
end

function HLY:HandleMarkerUpdate()
    self:QueueMarkerMacroUpdate()
    self:RefreshMarkerReminder()
end

function HLY:HandleMarkerRegen()
    if self.markerPendingMacroUpdate then
        self:UpdateMarkerMacroNow()
    end
    self:RefreshMarkerReminder()
end

function HLY:SetupMarker()
    if self.markerSetup then return end

    self:SafeRegisterEvent("PLAYER_ENTERING_WORLD", "HandleMarkerUpdate")
    self:SafeRegisterEvent("GROUP_ROSTER_UPDATE", "HandleMarkerUpdate")
    self:SafeRegisterEvent("PLAYER_ROLES_ASSIGNED", "HandleMarkerUpdate")
    self:SafeRegisterEvent("ROLE_CHANGED_INFORM", "HandleMarkerUpdate")
    self:SafeRegisterEvent("ZONE_CHANGED_NEW_AREA", "HandleMarkerUpdate")
    self:SafeRegisterEvent("PLAYER_TARGET_CHANGED", "HandleMarkerUpdate")
    self:SafeRegisterEvent("RAID_TARGET_UPDATE", "HandleMarkerUpdate")
    self:SafeRegisterEvent("PLAYER_REGEN_ENABLED", "HandleMarkerRegen")

    self.markerSetup = true
    self:HandleMarkerUpdate()
end

-- LibHLYUI options pane (v2) ------------------------------------------------
local MARKER_ICONS = {
    { value = "0", text = "Kein Mark" },
    { value = "1", text = "|TInterface\TargetingFrame\UI-RaidTargetingIcon_1:0|t Stern" },
    { value = "2", text = "|TInterface\TargetingFrame\UI-RaidTargetingIcon_2:0|t Kreis" },
    { value = "3", text = "|TInterface\TargetingFrame\UI-RaidTargetingIcon_3:0|t Diamant" },
    { value = "4", text = "|TInterface\TargetingFrame\UI-RaidTargetingIcon_4:0|t Dreieck" },
    { value = "5", text = "|TInterface\TargetingFrame\UI-RaidTargetingIcon_5:0|t Mond" },
    { value = "6", text = "|TInterface\TargetingFrame\UI-RaidTargetingIcon_6:0|t Quadrat" },
    { value = "7", text = "|TInterface\TargetingFrame\UI-RaidTargetingIcon_7:0|t Kreuz" },
    { value = "8", text = "|TInterface\TargetingFrame\UI-RaidTargetingIcon_8:0|t Totenkopf" },
}

function HLY:BuildMarkerOptions(tab)
    tab:Note("Markiert den ersten zugewiesenen Tank in normalen Gruppen (nicht in Raids) mit einem Schlachtzugsymbol. Erstellt und pflegt automatisch das Makro 'HLYmarkerTank'; nutze es manuell, um die Markierung zu setzen.")
    tab:Row({
        function(c) c:Checkbox({ label = "Enable", get = function() return self.db.marker.enabled end,
            set = function(v) self.db.marker.enabled = v self:QueueMarkerMacroUpdate() self:RefreshMarkerReminder() end }) end,
        function(c) c:Button({ label = "Update Macro Now", func = function() self:UpdateMarkerMacroNow() end }) end,
    })
    tab:Dropdown({ label = "Tank Mark", values = MARKER_ICONS,
        get = function() return tostring(self.db.marker.mark) end,
        set = function(v) self.db.marker.mark = tonumber(v) or 6 self:QueueMarkerMacroUpdate() self:RefreshMarkerReminder() end })

    tab:Section("Reminder")
    tab:Slider({ label = "Font Size", min = 10, max = 36, step = 1,
        get = function() return self.db.marker.reminderFontSize end,
        set = function(v) self.db.marker.reminderFontSize = v self:RefreshMarkerReminder() end })
    tab:Row({
        function(c) c:Slider({ label = "X Offset", min = -2000, max = 2000, step = 1, labelWidth = 90,
            get = function() return self.db.marker.reminderX end,
            set = function(v) self.db.marker.reminderX = v self:RefreshMarkerReminder() end }) end,
        function(c) c:Slider({ label = "Y Offset", min = -1200, max = 1200, step = 1, labelWidth = 90,
            get = function() return self.db.marker.reminderY end,
            set = function(v) self.db.marker.reminderY = v self:RefreshMarkerReminder() end }) end,
    })
end

addon.options = addon.options or {}
addon.options[#addon.options + 1] = {
    group = "Other", groupOrder = 800, name = "Tank Marker", order = 1, groupAsEntry = true,
    build = "BuildMarkerOptions",
    onShow = "ShowMarkerReminderPreview", onHide = "HideMarkerReminderPreview",
}
