--========================================================
-- RE Health HUD — Toggle Button 
--========================================================

REHealthHUD_ToggleBtn = ISPanel:derive("REHealthHUD_ToggleBtn")

----------------------------------------------------------
-- Texture helper
----------------------------------------------------------
local function tex(path)
    return getTexture("42/" .. path) or getTexture(path)
end

BTN_TEX      = tex("media/ui/button/button.png")
BTN_TEX_DOWN = tex("media/ui/button/button_pressed.png")

----------------------------------------------------------
-- Apply Button Theme
----------------------------------------------------------
function applyBtnTheme()
    local style = REHUD_cfg.btnStyle or "1"

    if REHUD_cfg.iconStyle == "reverse" then
        BTN_TEX      = tex("media/ui/button/button_pressed" .. style .. ".png")
        BTN_TEX_DOWN = tex("media/ui/button/button" .. style .. ".png")
    else
        BTN_TEX      = tex("media/ui/button/button" .. style .. ".png")
        BTN_TEX_DOWN = tex("media/ui/button/button_pressed" .. style .. ".png")
    end
end

applyBtnTheme()

----------------------------------------------------------
-- Button Sizing
----------------------------------------------------------
function ensureButtonSize(btn)
    if not btn then return end

    local want = math.floor(40 * (REHUD_cfg.scale or 1))
    if btn.width ~= want or btn.height ~= want then
        btn:setWidth(want)
        btn:setHeight(want)

        local sw, sh = getCore():getScreenWidth(), getCore():getScreenHeight()
        btn:setX(math.max(0, math.min(btn.x, sw - btn.width)))
        btn:setY(math.max(0, math.min(btn.y, sh - btn.height)))
    end
end

----------------------------------------------------------
-- Constructor
----------------------------------------------------------
function REHealthHUD_ToggleBtn:new(x, y)
    local s = math.floor(40 * (REHUD_cfg.scale or 1))
    local o = ISPanel:new(x, y, s, s)

    setmetatable(o, self)
    self.__index = self

    o:initialise()
    o:addToUIManager()

    if o.setWantMouse then o:setWantMouse(true) end
    if o.setAlwaysOnTop then o:setAlwaysOnTop(false) end
    if o.setAlwaysBack then o:setAlwaysBack(false) end

    o.drag = false
    o.pressed = false
    o.menuOpen = false

    return o
end

----------------------------------------------------------
-- Render
----------------------------------------------------------
function REHealthHUD_ToggleBtn:prerender()
    ensureButtonSize(self)

    local useDown = self.pressed or self.menuOpen
    local t = useDown and BTN_TEX_DOWN or BTN_TEX

    if t then
		local brightness = REHUD_cfg.alpha or 0.70
		if brightness < 0 then brightness = 0 end
		if brightness > 1 then brightness = 1 end
		self:drawTextureScaled(t, 0, 0, self.width, self.height, brightness)
    else
        self:drawRectBorder(0, 0, self.width, self.height, 1, 1, 0, 0)
    end
end

----------------------------------------------------------
-- Mouse Handling
----------------------------------------------------------
function REHealthHUD_ToggleBtn:onMouseDown(x, y)
    playVanillaClick(self)

    if not REHUD_cfg.lockButton then
        self.drag = true
        self.dragOffX = x
        self.dragOffY = y
        self:setCapture(true)
    end

    self.pressed = true
    self:bringToTop()
end

function REHealthHUD_ToggleBtn:onMouseMove(dx, dy)
    if self.drag then
        local mx, my = getMouseX(), getMouseY()
        local nx = mx - (self.dragOffX or 0)
        local ny = my - (self.dragOffY or 0)

        local sw, sh = getCore():getScreenWidth(), getCore():getScreenHeight()
        self:setX(math.max(0, math.min(nx, sw - self.width)))
        self:setY(math.max(0, math.min(ny, sh - self.height)))
    end
end

function REHealthHUD_ToggleBtn:onMouseUp(x, y)
    self.pressed = false
    self:setCapture(false)

    if not REHUD_cfg.lockButton then
        self.drag = false
    end

    REHUD_cfg.btnX = self.x
    REHUD_cfg.btnY = self.y

    if REHUD_HUD then
        local v = not REHUD_HUD:getIsVisible()
        REHUD_HUD:setVisible(v)
        REHUD_cfg.winVisible = v

        if REHUD_cfg.uiSounds then
            playOgg(v and "Accept" or "Cancel")
        end
    end
end

function REHealthHUD_ToggleBtn:onMouseUpOutside()
    self.drag = false
    self.pressed = false
    self:setCapture(false)
end

function REHealthHUD_ToggleBtn:update()
    if self.menuOpen and not ISContextMenu.instance then
        self.menuOpen = false
        self.pressed = false
    end
end

function REHealthHUD_ToggleBtn:onRightMouseUp(x, y)
    playVanillaClick(self)

    local p = getSpecificPlayer(0) or getPlayer()
    if not p then return end

    local menu = ISContextMenu.get(p:getPlayerNum(), getMouseX(), getMouseY())
    if not menu then return end

    self.menuOpen = true

    local function L(str)
        return getText(str) or ("MISSING:" .. tostring(str))
    end

    local function pretty(str)
        if not str or str == "" then return L("UI_REH_Default") end
        str = tostring(str)
        return str:gsub("^%l", string.upper)
    end

    -------------------------------------------------------------------------
    -- OPTIONS
    -------------------------------------------------------------------------
    local opt = menu:addOption(L("UI_REH_Menu_Options"))
    local optSub = ISContextMenu:getNew(menu)
    menu:addSubMenu(opt, optSub)

    optSub:addOption(
        REHUD_cfg.lockButton and L("UI_REH_Options_UnlockButton") or L("UI_REH_Options_LockButton"),
        self,
        function()
            REHUD_cfg.lockButton = not REHUD_cfg.lockButton
            REHUD_WriteConfig()
        end
    )

    optSub:addOption(
        L("UI_REH_Options_DefaultHotbar") .. ": " .. (REHUD_cfg.hotbarDefault and L("UI_REH_On") or L("UI_REH_Off")),
        nil,
        function()
            REHUD_cfg.hotbarDefault = not REHUD_cfg.hotbarDefault
            REH.Slots.patchAll()
            REHUD_WriteConfig()
        end
    )

    -------------------------------------------------------------------------
    -- SOUND FX
    -------------------------------------------------------------------------
    local snd = menu:addOption(L("UI_REH_Menu_SoundFX"))
    local sndSub = ISContextMenu:getNew(menu)
    menu:addSubMenu(snd, sndSub)

    sndSub:addOption(
        L("UI_REH_Sound_InventorySFX") .. ": " .. (REHUD_cfg.uiClickSounds and L("UI_REH_On") or L("UI_REH_Off")),
        self,
        function()
            REHUD_cfg.uiClickSounds = not REHUD_cfg.uiClickSounds
            REHUD_WriteConfig()
        end
    )

    sndSub:addOption(
        L("UI_REH_Sound_OpenCloseSFX") .. ": " .. (REHUD_cfg.uiSounds and L("UI_REH_On") or L("UI_REH_Off")),
        self,
        function()
            REHUD_cfg.uiSounds = not REHUD_cfg.uiSounds
            REHUD_WriteConfig()
        end
    )

    local vParent = sndSub:addOption(L("UI_REH_Sound_Volume") .. " (" .. tostring(REHUD_cfg.uiVolume) .. "%)")
    local vMenu = ISContextMenu:getNew(sndSub)
    sndSub:addSubMenu(vParent, vMenu)

    for _, pct in ipairs({25,50,75,100}) do
        vMenu:addOption(
            pct .. "%",
            nil,
            function()
                REHUD_cfg.uiVolume = pct
                REHUD_WriteConfig()
            end
        )
    end

	-------------------------------------------------------------------------
	-- STATUS STYLE
	-------------------------------------------------------------------------
	local st = menu:addOption(L("UI_REH_Menu_StatusStyle"))
	local stSub = ISContextMenu:getNew(menu)
	menu:addSubMenu(st, stSub)
	
	-- Localised names for current theme
	local statusNames = {
		classic = L("UI_REH_Status_Classic"),
		modern  = L("UI_REH_Status_Modern"),
	}
	
	local stStyle = stSub:addOption(
		L("UI_REH_Status_Style") .. ": " .. (statusNames[REHUD_cfg.statusTheme] or L("UI_REH_Default"))
	)
	
	local stStyleSub = ISContextMenu:getNew(stSub)
	stSub:addSubMenu(stStyle, stStyleSub)
	
	stStyleSub:addOption(
		L("UI_REH_Status_Classic"),
		nil,
		function()
			REHUD_cfg.statusTheme = "classic"
			REHUD_WriteConfig()
		end
	)
	
	stStyleSub:addOption(
		L("UI_REH_Status_Modern"),
		nil,
		function()
			REHUD_cfg.statusTheme = "modern"
			REHUD_WriteConfig()
		end
	)
	
	stSub:addOption(
		L("UI_REH_Status_Link") .. ": " .. (REHUD_cfg.uiLink and L("UI_REH_On") or L("UI_REH_Off")),
		self,
		function()
			REHUD_cfg.uiLink = not REHUD_cfg.uiLink
			REHUD_WriteConfig()
		end
	)

    -------------------------------------------------------------------------
    -- EQUIPMENT STYLE
    -------------------------------------------------------------------------
    local eq = menu:addOption(L("UI_REH_Menu_EquipmentStyle"))
    local eqSub = ISContextMenu:getNew(menu)
    menu:addSubMenu(eq, eqSub)

    local eqList = {
        default = L("UI_REH_EquipmentTheme_Default"),
        crimson = L("UI_REH_EquipmentTheme_Crimson"),
        gold = L("UI_REH_EquipmentTheme_Gold"),
        gunmetal = L("UI_REH_EquipmentTheme_Gunmetal"),
        onyx = L("UI_REH_EquipmentTheme_Onyx"),
        sapphire = L("UI_REH_EquipmentTheme_Sapphire"),
        silver = L("UI_REH_EquipmentTheme_Silver")
    }

    local eqHeader = eqSub:addOption(L("UI_REH_Equipment_Style") .. ": " .. eqList[REHUD_cfg.uiTheme])
    local eqMenu = ISContextMenu:getNew(eqSub)
    eqSub:addSubMenu(eqHeader, eqMenu)

    for id, name in pairs(eqList) do
        eqMenu:addOption(name, nil, function()
            REHUD_cfg.uiTheme = id
            REHUD_SetBackgroundTheme(id)
            REHUD_WriteConfig()
        end)
    end

    local eqOpParent = eqSub:addOption(L("UI_REH_Equipment_Opacity") .. " (" .. math.floor((REHUD_cfg.equipAlpha or 1)*100) .. "%)")
    local eqOpMenu = ISContextMenu:getNew(eqSub)
    eqSub:addSubMenu(eqOpParent, eqOpMenu)

    for _, pct in ipairs({10,20,30,40,50,60,70,80,90,100}) do
        eqOpMenu:addOption(
            pct .. "%",
            nil,
            function()
                REHUD_cfg.equipAlpha = pct / 100
                REHUD_WriteConfig()
            end
        )
    end

    -------------------------------------------------------------------------
    -- INVENTORY STYLE (TETRIS)
    -------------------------------------------------------------------------
    local inv = menu:addOption(L("UI_REH_Menu_InventoryStyle"))
    local invSub = ISContextMenu:getNew(menu)
    menu:addSubMenu(inv, invSub)

    local invList = {
        default = L("UI_REH_InventoryTheme_Default"),
        crimson = L("UI_REH_InventoryTheme_Crimson"),
        gold = L("UI_REH_InventoryTheme_Gold"),
        gunmetal = L("UI_REH_InventoryTheme_Gunmetal"),
        onyx = L("UI_REH_InventoryTheme_Onyx"),
        sapphire = L("UI_REH_InventoryTheme_Sapphire"),
        silver = L("UI_REH_InventoryTheme_Silver")
    }

    local invHeader = invSub:addOption(L("UI_REH_Inventory_Style") .. ": " .. invList[REHUD_cfg.tetrisTheme])
    local invMenu = ISContextMenu:getNew(invSub)
    invSub:addSubMenu(invHeader, invMenu)

    for id, name in pairs(invList) do
        invMenu:addOption(name, nil, function()
            REHUD_cfg.tetrisTheme = id
            REHUD_SetTetrisTheme(id)
            REHUD_WriteConfig()
        end)
    end

    local invOpParent = invSub:addOption(L("UI_REH_Inventory_Opacity") .. " (" .. math.floor((REHUD_cfg.tetrisAlpha or 1)*100) .. "%)")
    local invOpMenu = ISContextMenu:getNew(invSub)
    invSub:addSubMenu(invOpParent, invOpMenu)

    for _, pct in ipairs({10,20,30,40,50,60,70,80,90,100}) do
        invOpMenu:addOption(
            pct .. "%",
            nil,
            function()
                REHUD_cfg.tetrisAlpha = pct / 100
                REHUD_WriteConfig()
            end
        )
    end

    local itemOpParent = invSub:addOption(L("UI_REH_Inventory_ItemOpacity") .. " (" .. math.floor((REHUD_cfg.itemBGOpacity or 1)*100) .. "%)")
    local itemOpMenu = ISContextMenu:getNew(invSub)
    invSub:addSubMenu(itemOpParent, itemOpMenu)

    for _, pct in ipairs({0,10,20,30,40,50,60,70,80,90,100}) do
        itemOpMenu:addOption(
            pct .. "%",
            nil,
            function()
                REHUD_cfg.itemBGOpacity = pct / 100
                REHUD_WriteConfig()
            end
        )
    end

    invSub:addOption(
        L("UI_REH_Inventory_ContainerBackground") .. ": " .. (REHUD_cfg.containerBG and L("UI_REH_On") or L("UI_REH_Off")),
        nil,
        function()
            REHUD_cfg.containerBG = not REHUD_cfg.containerBG
            REHUD_WriteConfig()
        end
    )

    -------------------------------------------------------------------------
    -- SLOT STYLE
    -------------------------------------------------------------------------
    local ic = menu:addOption(L("UI_REH_Menu_SlotStyle"))
    local icSub = ISContextMenu:getNew(menu)
    menu:addSubMenu(ic, icSub)

    local prettyNames = {
        black  = L("UI_REH_SlotTheme_Black"),
        blue   = L("UI_REH_SlotTheme_Blue"),
        gold   = L("UI_REH_SlotTheme_Gold"),
        green  = L("UI_REH_SlotTheme_Green"),
        red    = L("UI_REH_SlotTheme_Red"),
        silver = L("UI_REH_SlotTheme_Silver")
    }

    local icHeader = icSub:addOption(L("UI_REH_Slot_Style") .. ": " .. (prettyNames[REHUD_cfg.slotTheme] or L("UI_REH_Default")))
    local icMenu = ISContextMenu:getNew(icSub)
    icSub:addSubMenu(icHeader, icMenu)

    for id, name in pairs(prettyNames) do
        icMenu:addOption(name, nil, function()
            REHUD_cfg.slotTheme = id
            REH.Slots.applySavedTheme(id)
            REH.Slots.patchAll()
            REHUD_WriteConfig()
        end)
    end

    local shParent = icSub:addOption(L("UI_REH_Slot_Tint") .. " (" .. math.floor((REHUD_cfg.slotFade or 1)*100) .. "%)")
    local shMenu = ISContextMenu:getNew(icSub)
    icSub:addSubMenu(shParent, shMenu)

    for _, pct in ipairs({10,20,30,40,50,60,70,80,90,100}) do
        shMenu:addOption(
            pct .. "%",
            nil,
            function()
                REHUD_cfg.slotFade = pct / 100
                REHUD_WriteConfig()
            end
        )
    end
	
	-------------------------------------------------------------------------
	-- BUTTON
	-------------------------------------------------------------------------
	local bt = menu:addOption(L("UI_REH_Menu_Button"))
	local btSub = ISContextMenu:getNew(menu)
	menu:addSubMenu(bt, btSub)
	
	local btnNames = {
		["1"] = L("UI_REH_ButtonTheme_Umbrella"),
		["2"] = L("UI_REH_ButtonTheme_RPD"),
		["3"] = L("UI_REH_ButtonTheme_STARS"),
		["4"] = L("UI_REH_ButtonTheme_BSAA"),
	}
	
	local btHeader = btSub:addOption(
		L("UI_REH_Button_Style") .. ": " ..
		(btnNames[tostring(REHUD_cfg.btnStyle)] or L("UI_REH_ButtonTheme_Umbrella"))
	)
	
	local btMenu = ISContextMenu:getNew(btSub)
	btSub:addSubMenu(btHeader, btMenu)
	
	for id, name in pairs(btnNames) do
		btMenu:addOption(name, self, function()
			REHUD_cfg.btnStyle = tostring(id)
			applyBtnTheme()
			REHUD_WriteConfig()
		end)
	end
	
	-- Localised invert state
	local invertNames = {
		default = L("UI_REH_Default"),
		reverse = L("UI_REH_Reverse"),
	}
	
	btSub:addOption(
		L("UI_REH_Button_InvertButton") .. ": " .. (invertNames[REHUD_cfg.iconStyle] or L("UI_REH_Default")),
		self,
		function()
			REHUD_cfg.iconStyle =
				(REHUD_cfg.iconStyle == "default") and "reverse" or "default"
			applyBtnTheme()
			REHUD_WriteConfig()
		end
	)
	
	local sizeParent = btSub:addOption(
		L("UI_REH_Button_Size") .. " (" .. math.floor((REHUD_cfg.scale or 1)*100) .. "%)"
	)
	local sizeMenu = ISContextMenu:getNew(btSub)
	btSub:addSubMenu(sizeParent, sizeMenu)
	
	for _, pct in ipairs({50,60,70,80,90,100,110,120,130,140,150}) do
		sizeMenu:addOption(
			pct .. "%",
			nil,
			function()
				REHUD_cfg.scale = pct / 100
				ensureButtonSize(self)
				REHUD_WriteConfig()
			end
		)
	end
	
	local opParent = btSub:addOption(
		L("UI_REH_Button_Opacity") .. " (" .. math.floor((REHUD_cfg.alpha or 1)*100) .. "%)"
	)
	local opMenu = ISContextMenu:getNew(btSub)
	btSub:addSubMenu(opParent, opMenu)
	
	for _, pct in ipairs({30,40,50,60,70,80,90,100}) do
		opMenu:addOption(
			pct .. "%",
			nil,
			function()
				REHUD_cfg.alpha = math.max(0.30, pct / 100)
				REHUD_WriteConfig()
			end
		)
	end
end