local addonName, SinsToolkit = ...
local Core = CreateFrame("Frame")
SinsToolkit.Core = Core

local DB_DEFAULTS = {
    gearScannerEnabled = true,
    gearScannerMaxLevelDisable = true,
    gearScannerSilent = false,
    gearScannerLootDelay = 0.5,
    gearScannerScanOnLoot = true,
    gearScannerAllowUnbound = false,
    gearScannerMinimumUpgrade = 0,
    gearScannerScoreTooltips = true,
    gearScannerReasonsTooltips = false,
    gearScannerLockSlots = false,
    gearScannerLockedSlots = {},
    gearScannerAutoRollGreensBopBlues = false,
    gearScannerAutoRollBoeBlues = false,
    gearScannerAutoRollEpics = false,
    gearScannerRollNonGearLoot = false,
    gearScannerNeverAutoNeed = true,
    gearScannerAutoConfirmBindOther = false,
    gearScannerAutoConfirmBindBlues = false,
    gearScannerAutoConfirmBindEpics = false,
    gearScannerUsePawn = false,
    hideOutOfRangeErrors = false,
    keepPanelsOpen = false,
    automateGossip = false,
    automateGossipModifier = "SHIFT",
    gseAutoUnshift = false,
    professionItemHotkeyEnabled = false,
    professionItemHotkeyModifier = "ALT",
    wowheadSearchEnabled = false,
    blockedUIErrors = {},
    exportStrings = {},
    profileVaultBackups = {},
    featureOwners = {},
}

local function CopyDefaults(src)
    local out = {}
    for k, v in pairs(src) do
        if type(v) == "table" then out[k] = CopyDefaults(v) else out[k] = v end
    end
    return out
end

local function IsAddonLoaded(addon)
    if C_AddOns and C_AddOns.IsAddOnLoaded then
        return C_AddOns.IsAddOnLoaded(addon)
    end
    return IsAddOnLoaded and IsAddOnLoaded(addon)
end

function SinsToolkit.IsClassCodexAvailable()
    return IsAddonLoaded("ClassCodex") and ClassCodexData ~= nil
end

function SinsToolkit.IsGSEAvailable()
    return IsAddonLoaded("GSE")
end

function SinsToolkit.EnsureDB()
    SinsToolkitDB = SinsToolkitDB or {}
    for key, value in pairs(DB_DEFAULTS) do
        if SinsToolkitDB[key] == nil then
            SinsToolkitDB[key] = type(value) == "table" and CopyDefaults(value) or value
        end
    end
    SinsToolkitDB.blockedUIErrors = SinsToolkitDB.blockedUIErrors or {}
    SinsToolkitDB.exportStrings = SinsToolkitDB.exportStrings or {}
    SinsToolkitDB.profileVaultBackups = SinsToolkitDB.profileVaultBackups or {}
    SinsToolkitDB.featureOwners = SinsToolkitDB.featureOwners or {}
    SinsToolkitDB.gearScannerLockedSlots = SinsToolkitDB.gearScannerLockedSlots or {}
end

function SinsToolkit.ApplyDependencyGuards(printNotice)
    SinsToolkit.EnsureDB()

    if SinsToolkitDB.gearScannerEnabled and not SinsToolkit.IsClassCodexAvailable() then
        SinsToolkitDB.gearScannerEnabled = false
        if printNotice then
            print("|cff9b59b6[Sin's Toolkit]|r Gear Scanner disabled because ClassCodex is not installed or loaded.")
        end
    end

    if SinsToolkitDB.gseAutoUnshift and not SinsToolkit.IsGSEAvailable() then
        SinsToolkitDB.gseAutoUnshift = false
        if printNotice then
            print("|cff9b59b6[Sin's Toolkit]|r Auto Unshift for Druids disabled because GSE is not installed or loaded.")
        end
    end
end

function SinsToolkit.GetFeatureOwner(featureKey)
    SinsToolkit.EnsureDB()
    return SinsToolkitDB.featureOwners[featureKey] or "SINS"
end

function SinsToolkit.SetFeatureOwner(featureKey, owner)
    SinsToolkit.EnsureDB()
    SinsToolkitDB.featureOwners[featureKey] = owner == "SINS" and nil or owner
end

function SinsToolkit.IsFeatureOwnedByToolkit(featureKey)
    return SinsToolkit.GetFeatureOwner(featureKey) == "SINS"
end

function SinsToolkit.IsFeatureActive(featureKey)
    SinsToolkit.EnsureDB()
    if featureKey == "gearScannerEnabled" and not SinsToolkit.IsClassCodexAvailable() then return false end
    if featureKey == "gseAutoUnshift" and not SinsToolkit.IsGSEAvailable() then return false end
    return SinsToolkitDB[featureKey] == true and SinsToolkit.IsFeatureOwnedByToolkit(featureKey)
end

function SinsToolkit.TriggerUpdate(dbKey)
    if dbKey and dbKey:match("^gearScanner") and SinsToolkit.RefreshGearScannerScores then
        SinsToolkit.RefreshGearScannerScores()
    end
    if dbKey == "gearScannerEnabled" and SinsToolkitDB.gearScannerEnabled and not SinsToolkit.IsClassCodexAvailable() then
        SinsToolkitDB.gearScannerEnabled = false
        print("|cff9b59b6[Sin's Toolkit]|r Gear Scanner requires ClassCodex.")
        return
    end
    if dbKey == "gseAutoUnshift" and SinsToolkitDB.gseAutoUnshift and not SinsToolkit.IsGSEAvailable() then
        SinsToolkitDB.gseAutoUnshift = false
        print("|cff9b59b6[Sin's Toolkit]|r Auto Unshift for Druids requires GSE, also known as Gnome Sequencer.")
        return
    end
    if dbKey == "gseAutoUnshift" and SinsToolkit.ApplyGSEAutoUnshift then SinsToolkit.ApplyGSEAutoUnshift() end
    if dbKey == "professionItemHotkeyEnabled" and SinsToolkit.ApplyProfessionItemHotkeyEnabled then SinsToolkit.ApplyProfessionItemHotkeyEnabled() end
    if dbKey == "professionItemHotkeyModifier" and SinsToolkit.ApplyProfessionItemHotkeyModifier then
        SinsToolkit.ApplyProfessionItemHotkeyModifier(SinsToolkitDB.professionItemHotkeyModifier)
    end
    if dbKey == "keepPanelsOpen" then
        if SinsToolkit.ApplyNoAutoClosePanels then SinsToolkit.ApplyNoAutoClosePanels() end
        print("|cff9b59b6[Sin's Toolkit]|r No Auto Close Panels updated. Reload your UI after disabling it.")
    end
end

Core:RegisterEvent("PLAYER_LOGIN")
Core:SetScript("OnEvent", function(self, event, ...)
    if event == "PLAYER_LOGIN" then
        self:UnregisterEvent("PLAYER_LOGIN")
        SinsToolkit.EnsureDB()
        SinsToolkit.ApplyDependencyGuards(true)

        SLASH_SinsToolkit1 = "/stk"
        SlashCmdList.SinsToolkit = function(msg)
            msg = (msg or ""):lower():match("^%s*(.-)%s*$")
            if msg == "scan" then
                if SinsToolkit.ForceGearScan then
                    SinsToolkit.ForceGearScan()
                else
                    print("|cff9b59b6[Sin's Toolkit]|r Gear Scanner is unavailable or currently disabled.")
                end
            elseif msg == "status" then
                print("|cff9b59b6Sin's Toolkit|r status")
                print("  Gear Scanner: " .. (SinsToolkit.IsFeatureActive("gearScannerEnabled") and "|cff00ff00Enabled|r" or "|cffff4040Disabled|r"))
                print("  Auto Gossip: " .. (SinsToolkit.IsFeatureActive("automateGossip") and "|cff00ff00Enabled|r" or "|cffff4040Disabled|r") .. " (" .. (SinsToolkitDB.automateGossipModifier or "SHIFT") .. ")")
                print("  Profession Hotkey: " .. (SinsToolkit.IsFeatureActive("professionItemHotkeyEnabled") and "|cff00ff00Enabled|r" or "|cffff4040Disabled|r") .. " (" .. (SinsToolkitDB.professionItemHotkeyModifier or "ALT") .. ")")
                print("  Auto Unshift for Druids: " .. (SinsToolkit.IsFeatureActive("gseAutoUnshift") and "|cff00ff00Enabled|r" or "|cffff4040Disabled|r"))
            else
                print("|cff9b59b6Sin's Toolkit|r commands")
                print("  |cffd8a84a/stk status|r - Show Toolkit feature status.")
                print("  |cffd8a84a/stk scan|r - Run a manual gear scan.")
                print("  |cffd8a84a/ec|r - Open ElvUI and select the Sin's Toolkit plugin tab.")
            end
        end

        ---------------------------------------------------------------------------
        --  Hide UI Error Messages
        ---------------------------------------------------------------------------
        do
            local originalHandler = UIErrorsFrame and UIErrorsFrame:GetScript("OnEvent")
            local messageInfoCache = {}

            local function IsBlockedUIError(id, err)
                if not err then return false end
                local blocked = SinsToolkitDB and SinsToolkitDB.blockedUIErrors
                if not blocked then return false end

                local stringID = messageInfoCache[id]
                if stringID == nil then
                    stringID = (GetGameMessageInfo and id and GetGameMessageInfo(id)) or false
                    messageInfoCache[id] = stringID
                end

                if stringID and blocked[stringID] then return true end
                if ERR_TOO_FAR_TO_INTERACT and err == ERR_TOO_FAR_TO_INTERACT then
                    return blocked.ERR_TOO_FAR_TO_INTERACT == true
                end
                return err == "You need to be closer to interact with that target."
                    and blocked.ERR_TOO_FAR_TO_INTERACT == true
            end

            local function IsAutoUnshiftUIError(id, err)
                if not err then return false end
                if not (SinsToolkit.IsFeatureActive and SinsToolkit.IsFeatureActive("gseAutoUnshift")) then return false end

                local stringID = messageInfoCache[id]
                if stringID == nil then
                    stringID = (GetGameMessageInfo and id and GetGameMessageInfo(id)) or false
                    messageInfoCache[id] = stringID
                end

                return stringID == "SPELL_FAILED_NOT_SHAPESHIFT"
                    or (SPELL_FAILED_NOT_SHAPESHIFT and err == SPELL_FAILED_NOT_SHAPESHIFT)
                    or err == "You are in shapeshift form."
            end

            if UIErrorsFrame then
                UIErrorsFrame:SetScript("OnEvent", function(self, ev, id, err, ...)
                    if ev == "UI_ERROR_MESSAGE" and SinsToolkitDB and err then
                        if IsAutoUnshiftUIError(id, err) then
                            return
                        end
                        if SinsToolkit.IsFeatureActive
                           and SinsToolkit.IsFeatureActive("hideOutOfRangeErrors")
                           and IsBlockedUIError(id, err) then
                            return
                        end
                    end
                    if originalHandler then
                        return originalHandler(self, ev, id, err, ...)
                    end
                end)
            end
        end

        ---------------------------------------------------------------------------
        --  Auto Unshift for Druids
        ---------------------------------------------------------------------------
        -- Implemented in SinsToolkit_AutoUnshift.lua.
        ---------------------------------------------------------------------------
        --  No Auto Close Panels
        ---------------------------------------------------------------------------
        -- Implemented in SinsToolkit_NoAutoClose.lua.
        ---------------------------------------------------------------------------
        --  Automate Gossip
        ---------------------------------------------------------------------------
        do
            local f = CreateFrame("Frame")
            f:RegisterEvent("GOSSIP_SHOW")
            f:SetScript("OnEvent", function()
                if not (SinsToolkit.IsFeatureActive and SinsToolkit.IsFeatureActive("automateGossip")) then return end

                local modifier = SinsToolkitDB.automateGossipModifier or "SHIFT"
                if modifier == "SHIFT" and IsShiftKeyDown() then return end
                if modifier == "CTRL" and IsControlKeyDown() then return end
                if modifier == "ALT" and IsAltKeyDown() then return end

                local options = C_GossipInfo.GetOptions()
                if options and #options > 0 then
                    C_GossipInfo.SelectOption(options[1].gossipOptionID)
                end
            end)
        end

        ---------------------------------------------------------------------------
        --  Wowhead Quick Link
        ---------------------------------------------------------------------------
        -- Implemented in SinsToolkit_WowheadQuickLink*.lua.
    end
end)


