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},
}

local function ResolveCustomSongPath(path, isCustom)
    if not path then return nil end
	
    local filename = path:match("([^\\]+)$")
    if not filename then
        return path
	end
	
    if isCustom then
        return "Interface\\AddOns\\Pedro_Custom\\Media\\" .. filename
		else
        return "Interface\\AddOns\\Pedro\\Media\\" .. filename
	end
end



-- 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 10 custom songs
    if G and G.customSongs then
        local count = 0
        for _, s in ipairs(G.customSongs) do
            count = count + 1
            if count > 10 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
	
    -- Custom songs never use intensity variants
    if sound.isCustom then
        return ResolveCustomSongPath(sound.path, true)
	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 and 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 resolved = realPath
	
	if not resolved then
		print("Pedro: Failed to resolve sound path.")
		return false
	end
	
	local ok, handle = PlaySoundFile(resolved, pedroAudioChannel)
	local soundHandle = handle or ok  -- supports both return styles
	
	if type(soundHandle) ~= "number" then
		print("Pedro: Failed to play sound. Invalid handle.")
		return false
	end
	
	pedroPlayingID = soundHandle
	
	
    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 resolved = ResolveCustomSongPath(realPath, sound.isCustom)
	if not resolved then
		print("Pedro: Could not resolve file:", tostring(realPath))
		return
	end
	
	local ok, handle = PlaySoundFile(resolved, pedroAudioChannel)
	local soundHandle = handle or ok 
	
	if type(soundHandle) == "number" then
		G.lastHandle = soundHandle
		
		if PedroMainUI and PedroMainUI.stopBtn then
			PedroMainUI.stopBtn:Enable()
			PedroMainUI.stopBtn:GetFontString():SetTextColor(1, 1, 1)
		end
		else
		G.lastHandle = nil
		print("Pedro: Failed to play sound:", resolved)
	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

function StopPedroManual()
    -- Stop manual custom song
    if G.lastHandle then
        StopSound(G.lastHandle)
        G.lastHandle = nil
	end
	
    -- Stop built-in Pedro sound (if any)
    if pedroPlayingID then
        StopSound(pedroPlayingID)
        pedroPlayingID = nil
	end
	
    -- Stop animation instantly
    isAnimating = false
    isFadingOut = false
    PedroAnimationFrame:SetAlpha(0)
    PedroAnimationFrame:SetScript("OnUpdate", nil)
	
    -- Disable Stop button
    if PedroMainUI and PedroMainUI.stopBtn then
        PedroMainUI.stopBtn:Disable()
        PedroMainUI.stopBtn:GetFontString():SetTextColor(0.6, 0.6, 0.6)
	end
end
