-------------------------
-- AiB Co-Tank | Init
-- Frame-Erstellung, Events und Bootstrap
-- Wird als letztes im cotank-Ordner geladen
-------------------------

local ns = AiB.CoTank.ns
local K  = ns.K

local function InitializeFrame()
    if InCombatLockdown() then return end

    local db = ns.DB()

    local frame = CreateFrame("Button", "AiB_CoTankFrame", UIParent,
        "SecureUnitButtonTemplate, BackdropTemplate")
    frame:SetAttribute("type1", "target")   -- Linksklick targetet den Co-Tank

    Mixin(frame, ns.Mixin)

    frame:SetSize(db.frameWidth or K.DEFAULT_WIDTH, db.frameHeight or K.DEFAULT_HEIGHT)
    frame:SetMovable(true)
    frame:SetClampedToScreen(true)

    -- Hintergrund
    frame.bg = frame:CreateTexture(nil, "BACKGROUND")
    frame.bg:SetAllPoints()
    frame.bg:SetColorTexture(0.05, 0.07, 0.11, 0.92)
    frame:SetBackdrop({edgeFile = K.BACKDROP_TEXTURE, edgeSize = 1})
    frame:SetBackdropBorderColor(0.08, 0.12, 0.20, 1)

    -- Health Bar
    frame.health = CreateFrame("StatusBar", nil, frame)
    frame.health:SetPoint("TOPLEFT",     1, -1)
    frame.health:SetPoint("BOTTOMRIGHT", -1, K.POWER_BAR_HEIGHT + 2)
    frame.health.statusBarTextureString = db.barTexture or K.BACKDROP_TEXTURE
    frame.health:SetStatusBarTexture(frame.health.statusBarTextureString)

    -- Power Bar
    frame.power = CreateFrame("StatusBar", nil, frame)
    frame.power:SetHeight(K.POWER_BAR_HEIGHT)
    frame.power:SetPoint("TOPLEFT",     frame.health, "BOTTOMLEFT",  0, -1)
    frame.power:SetPoint("BOTTOMRIGHT", frame,        "BOTTOMRIGHT", -1, 1)
    frame.power.statusBarTextureString = db.barTexture or K.BACKDROP_TEXTURE
    frame.power:SetStatusBarTexture(frame.power.statusBarTextureString)
    frame.powerBG = frame.power:CreateTexture(nil, "BACKGROUND")
    frame.powerBG:SetAllPoints()
    frame.powerBG:SetColorTexture(0, 0, 0, 0.5)

    -- Name-Text
    local face     = db.fontFace     or K.DEFAULT_FONT_FACE
    local nameSize = db.nameFontSize or K.DEFAULT_NAME_FONT_SIZE
    local hpSize   = db.hpFontSize   or K.DEFAULT_HP_FONT_SIZE
    frame.nameText = frame.health:CreateFontString(nil, "OVERLAY", "TextStatusBarText")
    frame.nameText:SetFont(face, nameSize, "OUTLINE")
    frame.nameText:SetPoint("BOTTOMLEFT", frame.health, "LEFT", 6, 4)
    frame.nameText:SetJustifyH("LEFT")
    frame.nameText:SetIgnoreParentAlpha(false)
    frame.nameText.rawText = ""

    -- HP-Text
    frame.hpText = frame.health:CreateFontString(nil, "OVERLAY", "TextStatusBarText")
    frame.hpText:SetFont(face, hpSize, "OUTLINE")
    frame.hpText:SetPoint("TOPLEFT", frame.health, "LEFT", 6, -4)
    frame.hpText:SetJustifyH("LEFT")
    frame.hpText:SetTextColor(0.9, 0.9, 0.9)
    frame.hpText:SetIgnoreParentAlpha(false)

    -- Aura / Debuff / Defensive Container
    -- Frame-Referenz VOR CreatePrivateAnchorContainers setzen
    -- (ApplyPrivateAuraGrow braucht AiB.CoTank.frame fuer Positionierung)
    AiB.CoTank.frame = frame

    frame:CreateDebuffContainer()
    frame:CreateDefensiveContainer()
    frame:CreatePrivateAnchorContainers()
    frame:CreateDeadOverlay()

    -- Click-Through
    if db.clickThrough then frame:EnableMouse(false) end

    -- Frame-Scripts
    frame:SetScript("OnAttributeChanged", frame.OnAttributeChanged)
    frame:SetScript("OnSizeChanged",      function(s, w, h) s:OnSizeChangedHandler(w, h) end)
    frame:SetScript("OnEvent",            frame.UpdateVisuals)
    frame:SetScript("OnShow", function(self)
        self:UpdateHealthBarColor()
        self:AttachPrivateAnchors()
    end)
    frame:SetScript("OnHide",    function(self) self:CleanupPrivateAnchors() end)
    frame:SetScript("OnMouseUp", function(self, btn)
        if btn == "RightButton" and not InCombatLockdown() then
            ns.Options:Open()
        end
    end)
    frame:RegisterForDrag("LeftButton")
    frame:SetScript("OnDragStart", function(self)
        if not InCombatLockdown() and not (ns.DB().frameLocked) then
            self:StartMoving()
        end
    end)
    frame:SetScript("OnDragStop", function(self)
        self:StopMovingOrSizing()
        ns.SavePosition(self)
    end)

    -- Position anwenden
    ns.ApplyPosition(frame)

    -- Gruppen / Rollen-Manager
    local manager = CreateFrame("Frame")
    manager:RegisterEvent("GROUP_ROSTER_UPDATE")
    manager:RegisterEvent("PLAYER_REGEN_ENABLED")
    manager:RegisterEvent("PLAYER_ENTERING_WORLD")
    manager:SetScript("OnEvent", function(_, event)
        if InCombatLockdown() then return end
        if not frame.anchorFrames then frame:CreatePrivateAnchorContainers() end
        local myRole      = UnitGroupRolesAssigned("player")
        local currentTank = ns.FindCoTank()
        if myRole == "TANK" and currentTank then
            frame:SetAttribute("unit", currentTank)
            RegisterUnitWatch(frame)
        else
            UnregisterUnitWatch(frame)
            frame:Hide()
            frame:SetAttribute("unit", nil)
        end
        frame:UpdateHealthBarColor()
        frame:UpdateVisuals()
        frame:RefreshAuraLayout()
        frame:RefreshDebuffLayout()
        frame:RefreshDefensiveLayout()
    end)

    -- Clique-Support
    _G["ClickCastFrames"]        = _G["ClickCastFrames"] or {}
    _G["ClickCastFrames"][frame] = true

    -- Alert, MyAuras und Options initialisieren
    ns.Alert:Initialize()
    ns.MyAuras:Initialize()
    ns.Options:Initialize()

    AiB.CoTank.UpdateDisplay = function() frame:UpdateVisuals() end

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

-- ── Bootstrap ──────────────────────────────────────────────────────────────
local loader = CreateFrame("Frame")
loader:RegisterEvent("PLAYER_LOGIN")
loader:SetScript("OnEvent", function(self, event)
    self:UnregisterEvent("PLAYER_LOGIN")
    local ok, err = pcall(InitializeFrame)
    if not ok then
        print("|cffff4040AiB CoTank load error:|r " .. tostring(err))
    end
end)
