-------------------------
-- AiB BreakTimer
-------------------------
-- Pause-Timer mit Meme-Anzeige

AiB_BreakTimer = AiB_BreakTimer or {}
local BT = AiB_BreakTimer

-- v2.1.0.0: AiB_BreakTimerConfig ist Alias auf AiB.db.profile.breaktimer (AceDB)
-- Config ist immer gesetzt wenn ADDON_LOADED gefeuert hat.
AiB_BreakTimerConfig = AiB_BreakTimerConfig or nil  -- Fallback vor ADDON_LOADED

-- State
BT.frame = nil
BT.duration = 0
BT.endTime = 0
BT.isRunning = false
BT.currentMeme = nil
BT.memeIndex = 1

-- Constants
local DBM_PREFIX = "D5"

-------------------------
-- Initialize
-------------------------
local function Initialize()
    -- Wait for SavedVariables
    C_Timer.After(2, function()
        -- v2.1.0.0: Config kommt aus AceDB-Profil; kein manueller Init nötig
        -- Fallback falls ADDON_LOADED noch nicht gefeuert hat (sollte nicht vorkommen)
        if not AiB_BreakTimerConfig then
            AiB_BreakTimerConfig = {
                enabled = true, width = 300, height = 25,
                barColor = {r=1, g=0.7, b=0, a=1},
                position = {point="CENTER", x=0, y=200},
                locked = true, soundEnabled = true,
                soundFile = "Interface\\AddOns\\AiB\\sounds\\break_default.ogg",
                memesEnabled = true, memeInterval = 30, memeWidth = 600, memeHeight = 400,
            }
        end
        
        BT:CreateFrame()
        BT:RegisterEvents()
    end)
end

-------------------------
-- Create Frame
-------------------------
function BT:CreateFrame()
    if self.frame then return end
    
    local f = CreateFrame("Frame", "AiB_BreakTimerFrame", UIParent, "BackdropTemplate")
    
    -- Position
    local point = AiB_BreakTimerConfig.position.point or "CENTER"
    local x = AiB_BreakTimerConfig.position.x or 0
    local y = AiB_BreakTimerConfig.position.y or 200
    
    f:SetPoint(point, UIParent, point, x, y)
    f:SetSize(AiB_BreakTimerConfig.width, AiB_BreakTimerConfig.height)
    f:SetMovable(true)
    f:EnableMouse(true)
    f:RegisterForDrag("LeftButton")
    f:SetClampedToScreen(true)
    f:Hide()
    
    -- Drag handlers
    f:SetScript("OnDragStart", function(self)
        if not AiB_BreakTimerConfig.locked then
            self:StartMoving()
        end
    end)
    
    f:SetScript("OnDragStop", function(self)
        self:StopMovingOrSizing()
        local point, _, _, x, y = self:GetPoint()
        AiB_BreakTimerConfig.position = {point = point, x = x, y = y}
    end)
    
    -- Background
    f:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8X8",
        edgeFile = "Interface\\Buttons\\WHITE8X8",
        tile = false,
        edgeSize = 2,
        insets = {left = 0, right = 0, top = 0, bottom = 0}
    })
    f:SetBackdropColor(0, 0, 0, 0.8)
    f:SetBackdropBorderColor(1, 0.8, 0, 1)
    
    -- Status Bar
    local bar = CreateFrame("StatusBar", nil, f)
    bar:SetAllPoints(f)
    bar:SetStatusBarTexture("Interface\\TargetingFrame\\UI-StatusBar")
    bar:SetMinMaxValues(0, 1)
    bar:SetValue(1)
    local c = AiB_BreakTimerConfig.barColor
    bar:SetStatusBarColor(c.r, c.g, c.b, c.a)
    f.bar = bar
    
    -- Text
    local text = bar:CreateFontString(nil, "OVERLAY")
    text:SetFont("Fonts\\FRIZQT__.TTF", 14, "OUTLINE")
    text:SetPoint("CENTER", bar, "CENTER", 0, 0)
    text:SetText("Pause: 00:00")
    text:SetTextColor(1, 1, 1, 1)
    f.text = text
    
    -- Spark
    local spark = bar:CreateTexture(nil, "OVERLAY")
    spark:SetTexture("Interface\\CastingBar\\UI-CastingBar-Spark")
    spark:SetBlendMode("ADD")
    spark:SetWidth(20)
    spark:SetHeight(AiB_BreakTimerConfig.height * 2)
    f.spark = spark
    
    -- Meme Display (above bar)
    local memeFrame = CreateFrame("Frame", nil, f)
    memeFrame:SetPoint("BOTTOM", f, "TOP", 0, 5)
    memeFrame:SetSize(AiB_BreakTimerConfig.memeWidth, AiB_BreakTimerConfig.memeHeight)
    -- KEIN Backdrop mehr - transparenter Hintergrund!
    f.memeFrame = memeFrame
    
    -- Meme Texture (wird proportional skaliert)
    local memeTex = memeFrame:CreateTexture(nil, "ARTWORK")
    memeTex:SetTexture("Interface\\Icons\\INV_Misc_QuestionMark") -- Placeholder
    -- WICHTIG: Nicht SetAllPoints - wir setzen die Größe manuell für Aspect Ratio!
    memeTex:SetPoint("CENTER", memeFrame, "CENTER", 0, 0)
    f.memeTex = memeTex
    
    -- Aspect Ratio Helper
    f.UpdateMemeAspectRatio = function(self)
        local frameWidth = self.memeFrame:GetWidth()
        local frameHeight = self.memeFrame:GetHeight()
        
        -- Hole Texture-Dimensionen (wenn möglich)
        local texWidth, texHeight = self.memeTex:GetTexture() and 1, 1 -- Fallback 1:1
        
        -- Berechne Skalierung um Aspect Ratio zu behalten
        local frameAspect = frameWidth / frameHeight
        local texAspect = texWidth / texHeight
        
        if texAspect > frameAspect then
            -- Bild ist breiter -> an Breite anpassen
            self.memeTex:SetWidth(frameWidth)
            self.memeTex:SetHeight(frameWidth / texAspect)
        else
            -- Bild ist höher -> an Höhe anpassen
            self.memeTex:SetHeight(frameHeight)
            self.memeTex:SetWidth(frameHeight * texAspect)
        end
    end
    
    -- Initial aspect ratio
    f:UpdateMemeAspectRatio()
    
    -- OnUpdate
    f:SetScript("OnUpdate", function(self, elapsed)
        if not BT.isRunning then return end
        
        local now = GetTime()
        local remaining = BT.endTime - now
        
        if remaining <= 0 then
            BT:StopTimer()
            BT:PlaySound()
            return
        end
        
        -- Update bar
        local pct = remaining / BT.duration
        self.bar:SetValue(pct)
        
        -- Update text
        local m = math.floor(remaining / 60)
        local s = math.floor(remaining % 60)
        self.text:SetText(string.format("Pause: %d:%02d", m, s))
        
        -- Update spark position
        local width = self:GetWidth()
        self.spark:SetPoint("CENTER", self.bar, "LEFT", width * pct, 0)
    end)
    
    self.frame = f
end

-------------------------
-- Start Timer
-------------------------
function BT:StartTimer(seconds)
    if not AiB_BreakTimerConfig.enabled then return end
    
    self.duration = seconds
    self.endTime = GetTime() + seconds
    self.isRunning = true
    
    if self.frame then
        self.frame:Show()
        self.frame.bar:SetValue(1)
        
        -- Start meme rotation
        if AiB_BreakTimerConfig.memesEnabled then
            self:StartMemeRotation()
        end
    end
end

-------------------------
-- Stop Timer
-------------------------
function BT:StopTimer()
    self.isRunning = false
    
    if self.frame then
        if AiB_BreakTimerConfig.locked then
            self.frame:Hide()
        end
        
        -- Stop meme rotation
        if self.memeTimer then
            self.memeTimer:Cancel()
            self.memeTimer = nil
        end
    end
end

-------------------------
-- Start Meme Rotation
-------------------------
function BT:StartMemeRotation()
    if not AiB_BreakTimerConfig.memesEnabled then return end
    
    -- Show first meme
    self:ShowRandomMeme()
    
    -- Rotate every X seconds
    if self.memeTimer then
        self.memeTimer:Cancel()
    end
    
    self.memeTimer = C_Timer.NewTicker(AiB_BreakTimerConfig.memeInterval, function()
        if BT.isRunning then
            BT:ShowRandomMeme()
        end
    end)
end

-------------------------
-- Show Random Meme
-------------------------
function BT:ShowRandomMeme()
    -- Get available memes
    local memes = BT:GetMemeList()
    
    if #memes == 0 then
        -- No memes available - show placeholder
        if self.frame and self.frame.memeTex then
            self.frame.memeTex:SetTexture("Interface\\Icons\\INV_Misc_QuestionMark")
            self.frame:UpdateMemeAspectRatio()
        end
        return
    end
    
    -- Pick random meme
    local randomIndex = math.random(1, #memes)
    local memePath = memes[randomIndex]
    
    if self.frame and self.frame.memeTex then
        self.frame.memeTex:SetTexture(memePath)
        self.currentMeme = memePath
        
        -- Update aspect ratio nach Texture-Load
        C_Timer.After(0.1, function()
            if BT.frame and BT.frame.UpdateMemeAspectRatio then
                BT.frame:UpdateMemeAspectRatio()
            end
        end)
    end
end

-------------------------
-- Get Meme List
-------------------------
function BT:GetMemeList()
    -- This will be populated by aib_breaktimer_memes.lua
    return AiB_BreakTimer_Memes or {}
end

-------------------------
-- Play Sound
-------------------------
function BT:PlaySound()
    if not AiB_BreakTimerConfig.soundEnabled then return end
    
    local soundFile = AiB_BreakTimerConfig.soundFile
    if soundFile and soundFile ~= "" then
        PlaySoundFile(soundFile, "Master")
    end
end

-------------------------
-- Slash Command Handler
-------------------------
function BT:SlashHandler(input)
    if not AiB_BreakTimerConfig.enabled then
        print("|cFFFF0000[AiB]|r BreakTimer ist deaktiviert!")
        return
    end
    
    -- Check restricted environment
    if IsEncounterInProgress() then
        print("|cFFFF0000[AiB]|r Kann keinen Timer während eines Encounters starten!")
        return
    end
    
    input = input or ""
    local args = {strsplit(" ", input)}
    local arg1 = args[1]
    
    if not arg1 or arg1 == "" then
        -- Cancel timer
        self:SendSync(0)
        self:StopTimer()
        print("|cFF00FF00[AiB]|r Pause abgebrochen.")
    else
        local minutes = tonumber(arg1)
        if minutes then
            local seconds = minutes * 60
            self:SendSync(seconds)
            self:StartTimer(seconds)
            print(string.format("|cFF00FF00[AiB]|r Pause gestartet für %d Minuten.", minutes))
        else
            print("|cFFFF0000[AiB]|r Verwendung: /break <minuten>")
        end
    end
end

-------------------------
-- Send Sync
-------------------------
function BT:SendSync(seconds)
    if IsEncounterInProgress() then return end
    
    local playerName = UnitName("player")
    local realmName = (GetRealmName() or ""):gsub("%s+", "")
    local fullName = playerName .. "-" .. realmName
    local msg = string.format("%s\t1\tBT\t%d", fullName, seconds)
    
    local channel = "NONE"
    if IsInGroup(LE_PARTY_CATEGORY_INSTANCE) then
        channel = "INSTANCE_CHAT"
    elseif IsInRaid() then
        channel = "RAID"
    elseif IsInGroup() then
        channel = "PARTY"
    end
    
    if channel ~= "NONE" then
        C_ChatInfo.SendAddonMessage(DBM_PREFIX, msg, channel)
    end
end

-------------------------
-- Receive Sync
-------------------------
function BT:OnCommReceived(prefix, message, distribution, sender)
    if not AiB_BreakTimerConfig.enabled then return end
    if prefix ~= DBM_PREFIX then return end
    if sender == UnitName("player") then return end
    
    local senderName, protocol, cmd, arg1 = strsplit("\t", message)
    if cmd == "BT" then
        local secs = tonumber(arg1)
        if secs then
            if secs > 0 then
                print(string.format("|cFF00FF00[AiB]|r Pause gestartet von %s", senderName or "Unbekannt"))
                self:StartTimer(secs)
            else
                self:StopTimer()
                print(string.format("|cFF00FF00[AiB]|r Pause abgebrochen von %s", senderName or "Unbekannt"))
            end
        end
    end
end

-------------------------
-- Register Events
-------------------------
function BT:RegisterEvents()
    -- Register addon message
    C_ChatInfo.RegisterAddonMessagePrefix(DBM_PREFIX)
    
    local eventFrame = CreateFrame("Frame")
    eventFrame:RegisterEvent("CHAT_MSG_ADDON")
    
    eventFrame:SetScript("OnEvent", function(self, event, prefix, message, distribution, sender)
        if event == "CHAT_MSG_ADDON" then
            BT:OnCommReceived(prefix, message, distribution, sender)
        end
    end)
end

-------------------------
-- Update Frame Layout
-------------------------
function BT:UpdateLayout()
    if not self.frame then return end
    
    self.frame:SetSize(AiB_BreakTimerConfig.width, AiB_BreakTimerConfig.height)
    
    local c = AiB_BreakTimerConfig.barColor
    self.frame.bar:SetStatusBarColor(c.r, c.g, c.b, c.a)
    
    self.frame.spark:SetHeight(AiB_BreakTimerConfig.height * 2)
    
    if self.frame.memeFrame then
        self.frame.memeFrame:SetSize(AiB_BreakTimerConfig.memeWidth, AiB_BreakTimerConfig.memeHeight)
        -- Update aspect ratio nach Größenänderung
        self.frame:UpdateMemeAspectRatio()
    end
    
    -- Show/hide based on lock
    if not AiB_BreakTimerConfig.locked then
        self.frame:Show()
        self.frame.text:SetText("Verschiebe mich")
        self.frame:EnableMouse(true)
    else
        if not self.isRunning then
            self.frame:Hide()
        end
        self.frame:EnableMouse(false)
    end
end

-------------------------
-- Slash Commands
-------------------------
SLASH_AIBBREAK1 = "/break"
SLASH_AIBBREAK2 = "/pause"
SlashCmdList["AIBBREAK"] = function(msg)
    BT:SlashHandler(msg)
end

-------------------------
-- Initialize on Login
-------------------------
local initFrame = CreateFrame("Frame")
initFrame:RegisterEvent("PLAYER_LOGIN")
initFrame:SetScript("OnEvent", function()
    Initialize()
end)
