-------------------------
-- AiB Co-Tank Frame
-- Zeigt die HP des zweiten Tanks im Raid
-- Nur sichtbar wenn Spieler Tank-Spec ist und ein zweiter Tank im Raid ist
-------------------------

AiB.CoTank = AiB.CoTank or {}

local currentOtherTank = nil

-------------------------
-- FRAME ERSTELLEN
-- SecureUnitButtonTemplate damit Klick = Target funktioniert
-------------------------
local frame = CreateFrame("Button", "AiB_CoTankFrame", UIParent, "SecureUnitButtonTemplate,BackdropTemplate")
frame:SetSize(150, 20)
frame:SetPoint("CENTER", UIParent, "CENTER", 200, 0)
frame:RegisterForClicks("AnyUp")
frame:SetAttribute("type1", "target")
frame:Hide()

-- Rahmen
local borderFrame = CreateFrame("Frame", nil, frame, "BackdropTemplate")
borderFrame:SetPoint("TOPLEFT", -1, 1)
borderFrame:SetPoint("BOTTOMRIGHT", 1, -1)
borderFrame:SetBackdrop({ edgeFile = "Interface\\Buttons\\WHITE8X8", edgeSize = 1 })
borderFrame:SetBackdropBorderColor(0, 0, 0, 1)

-- Hintergrund
local healthBg = frame:CreateTexture(nil, "BACKGROUND")
healthBg:SetAllPoints()
healthBg:SetColorTexture(0.1, 0.1, 0.1, 0.8)

-- Health Bar
local healthBar = CreateFrame("StatusBar", nil, frame)
healthBar:SetAllPoints()
healthBar:SetStatusBarTexture("Interface\\Buttons\\WHITE8X8")
healthBar:SetStatusBarColor(1, 0, 0, 1)  -- AiB Rot
healthBar:SetMinMaxValues(0, 100)
healthBar:SetValue(100)

-- Name Text
local nameText = healthBar:CreateFontString(nil, "OVERLAY")
nameText:SetFont("Fonts\\FRIZQT__.TTF", 12, "OUTLINE")
nameText:SetPoint("CENTER", healthBar, "CENTER", 0, 0)

-------------------------
-- HILFSFUNKTIONEN
-------------------------
local function GetDB()
    return AiB_CoTankConfig or (AiB.db and AiB.db.profile and AiB.db.profile.coTank)
end

local function FindOtherTank()
    if not IsInRaid() then return nil end
    local numMembers = GetNumGroupMembers()
    for i = 1, numMembers do
        local unit = "raid" .. i
        if UnitExists(unit) and not UnitIsUnit(unit, "player") then
            if UnitGroupRolesAssigned(unit) == "TANK" then
                return unit
            end
        end
    end
    return nil
end

local function IsPlayerTankSpec()
    if PlayerUtil and PlayerUtil.IsPlayerEffectivelyTank then
        return PlayerUtil.IsPlayerEffectivelyTank()
    end
    return UnitGroupRolesAssigned("player") == "TANK"
end

local function ShouldBeVisible()
    local db = GetDB()
    if not db or not db.enabled then return false end
    if db.unlock then return true end
    if not IsInRaid() then return false end
    if not IsPlayerTankSpec() then return false end
    return FindOtherTank() ~= nil
end

-------------------------
-- HEALTH UPDATE
-------------------------
local function UpdateHealth()
    local db = GetDB()
    if not db then return end
    if not currentOtherTank or not UnitExists(currentOtherTank) then
        healthBar:SetValue(0)
        nameText:Hide()
        return
    end

    healthBar:SetMinMaxValues(0, UnitHealthMax(currentOtherTank))
    healthBar:SetValue(UnitHealth(currentOtherTank))

    -- Farbe
    if db.useClassColor then
        local _, class = UnitClass(currentOtherTank)
        if class and RAID_CLASS_COLORS[class] then
            local c = RAID_CLASS_COLORS[class]
            healthBar:SetStatusBarColor(c.r, c.g, c.b)
        end
    else
        healthBar:SetStatusBarColor(
            db.healthColorR or 1,
            db.healthColorG or 0,
            db.healthColorB or 0)
    end

    -- Name
    if db.showName then
        local name = UnitName(currentOtherTank)
        if name then
            if db.nameFormat == "abbreviated" and db.nameLength then
                name = string.sub(name, 1, db.nameLength)
            end
            nameText:SetFont("Fonts\\FRIZQT__.TTF", db.nameFontSize or 12, "OUTLINE")
            nameText:SetText(name)
            if db.nameColorUseClassColor then
                local _, class = UnitClass(currentOtherTank)
                if class and RAID_CLASS_COLORS[class] then
                    local c = RAID_CLASS_COLORS[class]
                    nameText:SetTextColor(c.r, c.g, c.b)
                end
            else
                nameText:SetTextColor(
                    db.nameColorR or 1,
                    db.nameColorG or 1,
                    db.nameColorB or 1)
            end
            nameText:Show()
        else
            nameText:Hide()
        end
    else
        nameText:Hide()
    end
end

-------------------------
-- DISPLAY UPDATE
-------------------------
local function UpdateDisplay()
    local db = GetDB()
    if not db then
        if not InCombatLockdown() then frame:Hide() end
        return
    end

    if not InCombatLockdown() then
        frame:SetSize(db.width or 150, db.height or 20)
    end

    healthBg:SetAlpha(db.bgAlpha or 0.8)

    if ShouldBeVisible() then
        currentOtherTank = FindOtherTank()

        if not InCombatLockdown() then
            frame:SetAttribute("unit", currentOtherTank)
        end

        -- Preview wenn unlock aktiv aber kein Tank gefunden
        if db.unlock and not currentOtherTank then
            healthBar:SetValue(75)
            healthBar:SetMinMaxValues(0, 100)
            healthBar:SetStatusBarColor(1, 0, 0, 1)
            if db.showName then
                nameText:SetFont("Fonts\\FRIZQT__.TTF", db.nameFontSize or 12, "OUTLINE")
                nameText:SetText("TankName")
                nameText:SetTextColor(1, 1, 1)
                nameText:Show()
            else
                nameText:Hide()
            end
        else
            UpdateHealth()
        end

        if not InCombatLockdown() then frame:Show() end
    else
        if not InCombatLockdown() then
            frame:SetAttribute("unit", nil)
            frame:Hide()
        end
    end
end

-- Export für Settings
AiB.CoTank.frame = frame
AiB.CoTank.UpdateDisplay = UpdateDisplay

-------------------------
-- DRAG & DROP (nur außerhalb Kampf)
-------------------------
frame:SetMovable(true)
frame:SetClampedToScreen(true)
frame:RegisterForDrag("LeftButton")
frame:SetScript("OnDragStart", function(self)
    local db = GetDB()
    if db and db.unlock and not InCombatLockdown() then
        self:StartMoving()
    end
end)
frame:SetScript("OnDragStop", function(self)
    self:StopMovingOrSizing()
    local db = GetDB()
    if db then
        local point, _, _, x, y = self:GetPoint()
        db.point = point
        db.x = x
        db.y = y
    end
end)

-------------------------
-- EVENTS
-------------------------
local eventFrame = CreateFrame("Frame", "AiB_CoTankEvents")
eventFrame:RegisterEvent("PLAYER_LOGIN")
eventFrame:RegisterEvent("GROUP_ROSTER_UPDATE")
eventFrame:RegisterEvent("PLAYER_ROLES_ASSIGNED")
eventFrame:RegisterEvent("ROLE_CHANGED_INFORM")
eventFrame:RegisterEvent("PLAYER_SPECIALIZATION_CHANGED")
eventFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
eventFrame:RegisterEvent("PLAYER_REGEN_ENABLED")

eventFrame:SetScript("OnEvent", function(self, event)
    if event == "PLAYER_LOGIN" then
        local db = GetDB()
        if not db then return end
        -- Position laden
        if db.point then
            frame:ClearAllPoints()
            frame:SetPoint(db.point, UIParent, db.point, db.x or 200, db.y or 0)
        end
        UpdateDisplay()
        return
    end

    if event == "GROUP_ROSTER_UPDATE" or event == "PLAYER_ROLES_ASSIGNED"
       or event == "ROLE_CHANGED_INFORM" or event == "PLAYER_ENTERING_WORLD" then
        currentOtherTank = FindOtherTank()
        UpdateDisplay()
        return
    end

    if event == "PLAYER_SPECIALIZATION_CHANGED" then
        UpdateDisplay()
        return
    end

    if event == "PLAYER_REGEN_ENABLED" then
        currentOtherTank = FindOtherTank()
        if not InCombatLockdown() then
            frame:SetAttribute("unit", currentOtherTank)
        end
        UpdateDisplay()
        return
    end
end)

-- OnUpdate für Live-HP
local updateElapsed = 0
local updateFrame = CreateFrame("Frame", "AiB_CoTankUpdater")
updateFrame:SetScript("OnUpdate", function(self, elapsed)
    if not frame:IsShown() then return end
    updateElapsed = updateElapsed + elapsed
    if updateElapsed < 0.1 then return end
    updateElapsed = 0
    UpdateHealth()
end)

AiB.Config:Log("CoTank", "Modul geladen")
