G.lastHandle = nil

-- Base Pedro Sounds (built-in)
BasePedroSounds = {
    {name = "Pedro",      path = "Interface\\AddOns\\Pedro\\Media\\Pedro.ogg",      duration = 9},
    {name = "PedroLong",  path = "Interface\\AddOns\\Pedro\\Media\\PedroLong.ogg",  duration = 40},
    {name = "GoldenKpop", path = "Interface\\AddOns\\Pedro\\Media\\GoldenKpop.ogg", duration = 48},
}

-- Runtime list (base + up to 5 custom)
PedroSounds = {}
PedroSongLengths = {}

function RebuildPedroSounds()
    wipe(PedroSounds)
    wipe(PedroSongLengths)
    
    -- Add built-in sounds
    for _, s in ipairs(BasePedroSounds) do
        s.isCustom = false
        table.insert(PedroSounds, s)
	end
    
    -- Add up to 5 custom songs
    if G and G.customSongs then
        local count = 0
        for _, s in ipairs(G.customSongs) do
            count = count + 1
            if count > 5 then break end
            s.isCustom = true
            table.insert(PedroSounds, s)
		end
	end
    
    -- Build duration lookup
    for _, sound in ipairs(PedroSounds) do
        if sound.path and sound.duration then
            PedroSongLengths[sound.path] = sound.duration
		end
	end
end

function GetIntensityPath(sound)
	G.soundIntensity = G.soundIntensity or {}
	
	if not sound or not sound.path then
        return nil
	end
    if sound.isCustom then
        return sound.path
	end
	
    local intensity = G.soundIntensity[sound.path] or "normal"
	
    if intensity == "quiet" then
        return sound.path:gsub("%.ogg", "_Quiet.ogg")
		elseif intensity == "loud" then
        return sound.path:gsub("%.ogg", "_Loud.ogg")
		else
        return sound.path
	end
end


function GetSelectedSoundObject()
    for _, sound in ipairs(PedroSounds) do
        if sound.path == G.selectedSound then
            return sound
		end
	end
    return nil
end


-- Get length of selected song
function GetSelectedSongLength()
    if not PedroSongLengths[G.selectedSound] then
        -- Fallback to PedroLong
        G.selectedSound = BasePedroSounds[2].path
	end
	
    return PedroSongLengths[G.selectedSound] or 40
end


-- Core state variables
lustActive = false
canPlay = true
lastTriggerTime = nil
cooldown = 1.5
lustGuardDuration = 48 -- seconds between allowed Pedro triggers

pedroAudioChannel = G.audioChannel or "Master"
pedroPlayingID = nil

-- Reset cooldown
local function ResetCooldown()
    canPlay = true
end

-- Play Pedro sound if allowed
function PlayPedroIfAllowed(ignoreGuard)
    if not ignoreGuard then
        if not canPlay then return false end
        if lastTriggerTime and (GetTime() - lastTriggerTime) < lustGuardDuration then return false end
	end
	
    if type(pedroPlayingID) == "number" then
        StopSound(pedroPlayingID)
        pedroPlayingID = nil
	end
	
    local sound = GetSelectedSoundObject()
    local realPath = GetIntensityPath(sound)
    local id = PlaySoundFile(realPath, pedroAudioChannel)
	
    if not id then
        print("Pedro: Failed to play sound. File missing or invalid.")
        return false
	end
	
    pedroPlayingID = id
	
    if not ignoreGuard then
        canPlay = false
        lastTriggerTime = GetTime()
        C_Timer.After(cooldown, ResetCooldown)
	end
	
    return true
end


-- Main trigger logic
function TryPlayPedro()
    if not G.enabled then return false end
	
    local songLength = GetSelectedSongLength()
    local played = false
	
    local hasDebuff = CheckLustDebuffByID()
    lustActive = hasDebuff
	
    if hasDebuff then
        if not isAnimating then
            local playedSound = PlayPedroIfAllowed()
            if playedSound and not G.disableAnimation then
                StartAnimation(songLength)
			end
            played = playedSound
		end
	end
	
    return played
end

-- Manual play
function TryPlayPedroManual()
    if not G.enabled then
        print("Pedro: Addon is disabled.")
        return
	end
	
    if G.lastHandle then
        StopSound(G.lastHandle)
	end
	
    local sound = GetSelectedSoundObject()
    local realPath = GetIntensityPath(sound)
    local ok, handle = PlaySoundFile(realPath, G.selectedChannel)
	
    if ok then
        G.lastHandle = handle
		else
        G.lastHandle = nil
	end
	
    local soundName = "Unknown"
    for _, s in ipairs(PedroSounds) do
        if s.path == G.selectedSound then
            soundName = s.name
            break
		end
	end
	
    print("Pedro: Played " .. soundName .. " manually.")
	
    if not G.disableAnimation then
        local songLength = GetSelectedSongLength()
        StartAnimation(songLength)
	end
end




