--========================================================
-- RE Health HUD — Config 
--========================================================

REHUD_cfg = REHUD_cfg or {
    ------------------------------------------------------
    -- Button
    ------------------------------------------------------
    alpha = 0.80,
    scale = 1.00,
    lockButton = false,
    iconStyle = "default",
    btnStyle = "1",
    btnX = 70,  btnY = 120,

    ------------------------------------------------------
    -- HUD Window
    ------------------------------------------------------
    winVisible = true,
    winX = 142, winY = 20, winW = 350, winH = 150,

    ------------------------------------------------------
    -- Animation Opacity
    ------------------------------------------------------
    showBox   = true,
    animAlpha = 0.80,

    ------------------------------------------------------
    -- Equipment UI Theme
    ------------------------------------------------------
    equipAlpha = 1.0,

    ------------------------------------------------------
    -- Slot IconBG Theme
    ------------------------------------------------------
    slotTheme = "black",
    slotFade  = 0.50,

    ------------------------------------------------------
    -- Tetris UI Theme
    ------------------------------------------------------
    tetrisTheme = "default",
    tetrisAlpha = 1.0,
	itemBGOpacity = 1.0,
	containerBG = true,

    ------------------------------------------------------
    -- Health Status Theme 
    ------------------------------------------------------
    statusTheme = "modern",
	
    ------------------------------------------------------
    -- Behavior flags
    ------------------------------------------------------
    uiLink        = false,
    uiSounds      = true,
    uiVolume      = 50,
    uiClickSounds = true,
}

local REHUD_INI = "REInterface.ini"

----------------------------------------------------------
-- Helper: safeAdd
----------------------------------------------------------
function safeAdd(ev, fn)
    if ev and type(ev.Add) == "function" then ev.Add(fn) end
end

----------------------------------------------------------
-- Read INI
----------------------------------------------------------
function REHUD_ReadConfig()
    if REHUD_cfg.uiTheme and REHUD_SetBackgroundTheme then
        REHUD_SetBackgroundTheme(REHUD_cfg.uiTheme)
    end

    if REHUD_cfg.slotTheme and REH.Slots and REH.Slots.applySavedTheme then
        REH.Slots.applySavedTheme(REHUD_cfg.slotTheme)
        if REH.Slots.patchAll then REH.Slots.patchAll() end
    end

    if REHUD_cfg.tetrisTheme and REHUD_SetTetrisTheme then
        REHUD_SetTetrisTheme(REHUD_cfg.tetrisTheme)
    end

    local reader = getFileReader(REHUD_INI, true)
    if not reader then
        print("[REHealthHUD] No INI found — using defaults.")
        return
    end

    while true do
        local line = reader:readLine()
        if not line then break end

        local k, v = line:match("([^=]+)=([^=]+)")
        if k and v then
            v = v:gsub("\r",""):gsub("\n","")

            if v == "true" then
                v = true
            elseif v == "false" then
                v = false
            elseif tonumber(v) then
                v = tonumber(v)
            end

            REHUD_cfg[k] = v
        end
    end
    reader:close()
    print("[REHealthHUD] Loaded INI.")

    if REHUD_cfg.uiTheme and REHUD_SetBackgroundTheme then
        REHUD_SetBackgroundTheme(REHUD_cfg.uiTheme)
    end

    if REHUD_cfg.tetrisTheme and REHUD_SetTetrisTheme then
        REHUD_SetTetrisTheme(REHUD_cfg.tetrisTheme)
    end
end

----------------------------------------------------------
-- Write INI
----------------------------------------------------------
function REHUD_WriteConfig()
    REHUD_cfg.uiTheme = RE_UI_THEME
    REHUD_cfg.slotTheme = REH and REH.Slots and REH.Slots.getTheme and REH.Slots.getTheme() or REHUD_cfg.slotTheme
    REHUD_cfg.tetrisTheme = RE_TETRIS_THEME

    if REHUD_HUD and REHUD_HUD.getX then
        REHUD_cfg.winX = REHUD_HUD:getX()
        REHUD_cfg.winY = REHUD_HUD:getY()
        REHUD_cfg.winW = REHUD_HUD:getWidth()
        REHUD_cfg.winH = REHUD_HUD:getHeight()
        REHUD_cfg.winVisible = REHUD_HUD:getIsVisible()
    end

    if REHUD_BTN and REHUD_BTN.getX then
        REHUD_cfg.btnX = REHUD_BTN:getX()
        REHUD_cfg.btnY = REHUD_BTN:getY()
    end

    local file = getFileWriter(REHUD_INI, true, false)
    if not file then
        print("[REHealthHUD] Failed to save INI.")
        return
    end

    for k, v in pairs(REHUD_cfg or {}) do
        file:write(tostring(k) .. "=" .. tostring(v) .. "\n")
    end
    file:close()
    print("[REHealthHUD] Saved INI.")
end

_G.REHUD_cfg = REHUD_cfg

----------------------------------------------------------
-- ModData Sync
----------------------------------------------------------
function syncHUDToConfig()
    local player = getSpecificPlayer(0)
    if player then
        local pdata = player:getModData()
        pdata.REHealthHUD = pdata.REHealthHUD or {}

        for k, v in pairs(REHUD_cfg) do
            pdata.REHealthHUD.uiTheme = RE_UI_THEME
            pdata.REHealthHUD.tetrisTheme = RE_TETRIS_THEME
            pdata.REHealthHUD[k] = v
        end
    end
end

----------------------------------------------------------
-- Load from ModData
----------------------------------------------------------
function REHUD_LoadFromModData()
    local player = getSpecificPlayer(0)
    if not player then return end

    local pdata = player:getModData()
    if not pdata.REHealthHUD then return end

    for k, v in pairs(pdata.REHealthHUD) do

        if k == "uiTheme" and REHUD_SetBackgroundTheme then
            REHUD_SetBackgroundTheme(v)
        end

        if k == "slotTheme" and REH.Slots and REH.Slots.applySavedTheme then
            REH.Slots.applySavedTheme(v)
        end

        if k == "tetrisTheme" and REHUD_SetTetrisTheme then
            REHUD_SetTetrisTheme(v)
        end

        REHUD_cfg[k] = v
    end
end

----------------------------------------------------------
-- RESET ALL SETTINGS
----------------------------------------------------------
function REHUD_ResetAll()
    print("[REHealthHUD] Resetting all settings...")

    -- Delete INI
    deleteFile(REHUD_INI)

    -- Clear ModData
    local p = getSpecificPlayer(0)
    if p then
        p:getModData().REHealthHUD = {}
    end

    ------------------------------------------------------
    -- RELOAD DEFAULT CONFIG PROPERLY (NO dofile!)
    ------------------------------------------------------
    -- Recreate default table without wiping the reference
    for k in pairs(REHUD_cfg) do
        REHUD_cfg[k] = nil
    end

    local defaults = {
        alpha = 0.80,
        scale = 1.00,
        lockButton = false,
        iconStyle = "default",
        btnStyle = "1",
        btnX = 70, btnY = 120,

        winVisible = true,
        winX = 142, winY = 20, winW = 350, winH = 150,

        showBox = true,
        animAlpha = 0.80,

        equipAlpha = 1.0,

        slotTheme = "black",
        slotFade = 0.50,

        tetrisTheme = "default",
        tetrisAlpha = 1.0,
        itemBGOpacity = 1.0,
		containerBG = true,

        statusTheme = "modern",

        classicScale  = 4.359375,
        classicOffsetX = 0,
        classicOffsetY = 0,
        classicOffsetW = 0,
        classicOffsetH = 0,

        uiLink        = false,
        uiSounds      = true,
        uiVolume      = 50,
        uiClickSounds = true,
    }

    for k,v in pairs(defaults) do
        REHUD_cfg[k] = v
    end

    ------------------------------------------------------
    -- Reapply & respawn HUD
    ------------------------------------------------------
    if REHUD_SetBackgroundTheme then
        REHUD_SetBackgroundTheme(REHUD_cfg.uiTheme)
    end
    if REHUD_SetTetrisTheme then
        REHUD_SetTetrisTheme(REHUD_cfg.tetrisTheme)
    end
    if REH.Slots and REH.Slots.patchAll then
        REH.Slots.patchAll()
    end

    if spawnHUD then spawnHUD() end

    REHUD_WriteConfig()

    print("[REHealthHUD] Reset complete.")
end
