PedroMainUI = nil

function ResizePedroMainUI()
    if not PedroMainUI then return end
	
    local perCustom = 24
    local baseHeight = 540
	
    local totalSounds = #PedroSounds
    local baseSounds = (BasePedroSounds and #BasePedroSounds) or 3
	
    local customCount = totalSounds - baseSounds
    if customCount < 0 then customCount = 0 end
	
    local newHeight = baseHeight + (customCount * perCustom)
	
    if newHeight < baseHeight then newHeight = baseHeight end
    if newHeight > 700 then newHeight = 700 end
	
    PedroMainUI:SetHeight(newHeight)
end


function ShowPedroMainUI()
    if PedroMainUI then
        PedroMainUI:Show()
        PedroMainUI:Raise()
        return
	end
	
    local f = CreateFrame("Frame", "PedroMainUI", UIParent, "BasicFrameTemplateWithInset")
    PedroMainUI = f
    f:SetScale(1.0)
	
    if not tContains(UISpecialFrames, "PedroMainUI") then
        table.insert(UISpecialFrames, "PedroMainUI")
	end
	
    f:SetSize(350, 420)
    f:SetPoint("CENTER")
    f:SetMovable(true)
    f:EnableMouse(true)
    f:RegisterForDrag("LeftButton")
    f:SetScript("OnDragStart", f.StartMoving)
    f:SetScript("OnDragStop", f.StopMovingOrSizing)
	
    f.title = f:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    f.title:SetPoint("TOP", 0, -5)
    f.title:SetText("Pedro Settings")
	
    local enableCB = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
    enableCB:SetPoint("TOPLEFT", 15, -25)
    enableCB.text:SetText("Enable Pedro - Turns on/off the entire addon")
    enableCB:SetChecked(G.enabled)
    enableCB:SetScript("OnClick", function(self)
        G.enabled = self:GetChecked()
        print("Pedro: " .. (G.enabled and "Enabled" or "Disabled"))
	end)
	
    local animCB = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
    animCB:SetPoint("TOPLEFT", enableCB, "BOTTOMLEFT", 0, -2)
    animCB.text:SetText("Enable Animation")
    animCB:SetChecked(not G.disableAnimation)
    animCB:SetScript("OnClick", function(self)
        G.disableAnimation = not self:GetChecked()
        print("Pedro: Animation " .. (G.disableAnimation and "disabled" or "enabled"))
	end)
	
	local mmCB = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate")
	mmCB:SetPoint("TOPLEFT", animCB, "BOTTOMLEFT", 0, -2)
	mmCB.text:SetText("Show Minimap Icon (Ignored by icon collectors)")
	mmCB:SetChecked(not G.minimap.hide)
	
	mmCB:SetScript("OnClick", function(self)
		G.minimap.hide = not self:GetChecked()
		ApplyMinimapVisibility()
	end)
	
	
	
    local soundLabel = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    soundLabel:SetPoint("TOPLEFT", mmCB, "BOTTOMLEFT", 0, -6)
    soundLabel:SetText("Sound:")
	
    PedroMainUI.soundLabel = soundLabel
	
    local addSongBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    addSongBtn:SetSize(100, 22)
    addSongBtn:SetPoint("LEFT", soundLabel, "RIGHT", 10, 0)
    addSongBtn:SetText("Add Song")
    addSongBtn:SetScript("OnClick", function()
        ShowAddSongWindow()
	end)
	
    RefreshSoundListUI()
    ResizePedroMainUI()
	
    local channelLabel = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    local lastButton = PedroMainUI.soundButtons[#PedroMainUI.soundButtons]
    channelLabel:SetPoint("TOPLEFT", lastButton, "BOTTOMLEFT", 0, -6)
    channelLabel:SetText("Audio Channel:")
	
    PedroMainUI.channelLabel = channelLabel
    local previous = channelLabel
	
    local channelButtons = {}
    for i, channel in ipairs(PedroAudioChannels) do
        local btn = CreateFrame("CheckButton", nil, f, "UIRadioButtonTemplate")
        btn:SetPoint("TOPLEFT", previous, "BOTTOMLEFT", 0, -4)
        previous = btn
        btn.text:SetText(channel.name)
		
        if G.audioChannel == channel.value then
            btn:SetChecked(true)
		end
		
        btn:SetScript("OnClick", function(self)
            if not self:GetChecked() then
                self:SetChecked(true)
                return
			end
			
            for _, other in ipairs(channelButtons) do
                if other ~= self then other:SetChecked(false) end
			end
			
            G.audioChannel = channel.value
            pedroAudioChannel = channel.value
            print("Pedro: Audio channel set to " .. channel.name)
		end)
		
        table.insert(channelButtons, btn)
	end
	
    local resetBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    resetBtn:SetSize(140, 22)
    resetBtn:SetPoint("TOPLEFT", channelButtons[#channelButtons], "BOTTOMLEFT", 0, -6)
    resetBtn:SetText("Reset Audio Channel")
	
    resetBtn:SetScript("OnClick", function()
        G.audioChannel = "Master"
        pedroAudioChannel = "Master"
        print("Pedro: Audio channel reset to Master")
		
        for i, channel in ipairs(PedroAudioChannels) do
            local isMaster = (channel.value == "Master")
            channelButtons[i]:SetChecked(isMaster)
		end
	end)
	
    local speedLabel = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    speedLabel:SetPoint("TOPLEFT", resetBtn, "BOTTOMLEFT", 0, -6)
    speedLabel:SetText("Animation Speed:")
	
    local speeds = {
        {label = "Slow",   value = 0.30},
        {label = "Normal", value = 0.15},
        {label = "Fast",   value = 0.10},
        {label = "Turbo",  value = 0.05},
	}
	
    previous = speedLabel
    local speedButtons = {}
	
    for i, s in ipairs(speeds) do
        local btn = CreateFrame("CheckButton", nil, f, "UIRadioButtonTemplate")
		
        btn:SetPoint("TOPLEFT", previous, "BOTTOMLEFT", 0, -4)
        previous = btn
		
        btn.text:SetText(s.label)
		
        if G.animationSpeed == s.value then
            btn:SetChecked(true)
		end
		
        btn:SetScript("OnClick", function(self)
            if not self:GetChecked() then
                self:SetChecked(true)
                return
			end
			
            for _, other in ipairs(speedButtons) do
                if other ~= self then
                    other:SetChecked(false)
				end
			end
			
            G.animationSpeed = s.value
            print("Pedro: Animation speed set to " .. s.label)
		end)
		
        table.insert(speedButtons, btn)
	end
	
    local posBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    posBtn:SetSize(140, 22)
    posBtn:SetPoint("TOPLEFT", speedButtons[#speedButtons], "BOTTOMLEFT", 0, -6)
    posBtn:SetText("Position Animation")
	
    posBtn:SetScript("OnClick", function()
        if InCombatLockdown() then
            print("Pedro: Leave combat to move the animation.")
            return
		end
		
        if PedroPositioningMode then
            local point, _, relativePoint, xOfs, yOfs = PedroAnimationFrame:GetPoint()
            G.animPoint = { point = point, relativePoint = relativePoint, x = xOfs, y = yOfs }
			
            PedroPositioningMode = false
            PedroAnimationFrame:SetAlpha(0)
            PedroAnimationFrame:EnableMouse(false)
			
            if PedroAnimationFrame.closeBtn then
                PedroAnimationFrame.closeBtn:EnableMouse(false)
                PedroAnimationFrame.closeBtn:Hide()
			end
			
            print("Pedro: Animation position saved.")
            return
		end
		
        PedroPositioningMode = true
        PedroAnimationFrame:SetAlpha(1)
        PedroAnimationFrame:Raise()
        PedroAnimationFrame:EnableMouse(true)
		
        if not PedroAnimationFrame.closeBtn then
            local closeBtn = CreateFrame("Button", nil, PedroAnimationFrame, "UIPanelCloseButton")
            closeBtn:SetPoint("TOPRIGHT", PedroAnimationFrame, "TOPRIGHT", 0, 0)
            closeBtn:SetScript("OnClick", function()
                local point, _, relativePoint, xOfs, yOfs = PedroAnimationFrame:GetPoint()
                G.animPoint = { point = point, relativePoint = relativePoint, x = xOfs, y = yOfs }
				
                PedroPositioningMode = false
                PedroAnimationFrame:SetAlpha(0)
                PedroAnimationFrame:EnableMouse(false)
                closeBtn:EnableMouse(false)
                closeBtn:Hide()
			end)
            PedroAnimationFrame.closeBtn = closeBtn
			else
            PedroAnimationFrame.closeBtn:EnableMouse(true)
            PedroAnimationFrame.closeBtn:Show()
		end
		
        print("Pedro: Drag the animation. Click X or press the button again to finish.")
	end)
	
    local resetPosBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    resetPosBtn:SetSize(160, 22)
    resetPosBtn:SetPoint("TOPLEFT", posBtn, "BOTTOMLEFT", 0, -6)
    resetPosBtn:SetText("Reset Animation Position")
    resetPosBtn:SetScript("OnClick", function()
        PedroAnimationFrame:ClearAllPoints()
        PedroAnimationFrame:SetPoint("TOPLEFT", UIParent, "TOPLEFT", 100, -120)
        G.animPoint = { point = "TOPLEFT", relativePoint = "TOPLEFT", x = 100, y = -120 }
        print("Pedro: Animation position reset.")
	end)
	
    local playBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
	playBtn:SetSize(140, 22)
	playBtn:SetPoint("TOPLEFT", resetPosBtn, "BOTTOMLEFT", 0, -6)
	playBtn:SetText("Play Pedro Now")
	playBtn:SetScript("OnClick", TryPlayPedroManual)
	
	-- Create Stop button AFTER PedroMainUI = f exists
	local stopBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
	PedroMainUI.stopBtn = stopBtn
	
	stopBtn:SetSize(140, 22)
	stopBtn:SetPoint("LEFT", playBtn, "RIGHT", 10, 0)
	stopBtn:SetText("Stop Pedro")
	stopBtn:SetScript("OnClick", StopPedroManual)
	
	-- Start disabled (nothing is playing yet)
	stopBtn:Disable()
	stopBtn:GetFontString():SetTextColor(0.6, 0.6, 0.6)
	
	f.version = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
	f.version:SetPoint("TOPLEFT", playBtn, "BOTTOMLEFT", 0, -8)
	f.version:SetJustifyH("LEFT")
	f.version:SetText("Version: " .. ADDON_VERSION)
	
	C_Timer.After(0, function()
		if not f or not f:IsShown() then
			f:Show()
		end
		
		local top = f:GetTop()
		local bottom = f.version:GetBottom() or f:GetBottom()
		if top and bottom then
			local neededHeight = math.ceil(top - bottom + 18)
			if (f:GetHeight() or 0) < neededHeight then
				f:SetHeight(neededHeight)
			end
		end
	end)
	
	f:Show()
end
