--[[
============================================================
Decor Vendor Addon
© 2026 MidniteDestiny. All Rights Reserved.
============================================================

This file is part of the Decor Vendor addon.

All code, structure, and design are the intellectual
property of MidniteDestiny unless otherwise stated.

You may NOT:
• Copy, reproduce, or redistribute this code
• Modify and redistribute this code
• Use this code in other addons or projects

without explicit permission from the author.

This addon is distributed for personal use only.

============================================================
]]

local addonName, dv = ...

local frame = dv.frame
local LibDBIcon = LibStub("LibDBIcon-1.0", true)

dv.vendorSessionCache = dv.vendorSessionCache or {}
local vendorSessionCache = dv.vendorSessionCache

if not frame then
    print("|cffff4040DecorVendor Startup:|r dv.frame is missing. Make sure UI\\MainFrame.lua loads first.")
    return
end

-------------------------------------------------
-- Open Main UI
-------------------------------------------------

function dv.OpenMainUI()
    if C_HousingCatalog and C_HousingCatalog.RequestHousingMarketInfoRefresh then
        dv.waitingForMarketData = true
        C_HousingCatalog.RequestHousingMarketInfoRefresh()
    end

    if BuildVendorUI then
        BuildVendorUI()
    elseif dv.BuildVendorUI then
        dv.BuildVendorUI()
    end

    local mainFrame = dv.frame or frame

    if mainFrame then
        mainFrame:Show()
    end

	if dv.ShowMainHomePanel then
		dv.ShowMainHomePanel()
	end
end

-------------------------------------------------
-- Defaults
-------------------------------------------------

local function InitDefaults()
    vendorSettings = vendorSettings or {}

    vendorSettings.completedDrop = vendorSettings.completedDrop or {}
    vendorSettings.completedDropNoXP = vendorSettings.completedDropNoXP or {}
    vendorSettings.visited = vendorSettings.visited or {}
    vendorSettings.completedAchievs = vendorSettings.completedAchievs or {}

    if vendorSettings.showWaypointButton == nil then
        vendorSettings.showWaypointButton = false
    end

    if vendorSettings.showMinimapButton == nil then
        vendorSettings.showMinimapButton = true
    end

    if vendorSettings.closeOnEsc == nil then
        vendorSettings.closeOnEsc = true
    end

    if vendorSettings.scale == nil then
        vendorSettings.scale = 1.0
    end

    if vendorSettings.hideCompletedThings == nil then
        vendorSettings.hideCompletedThings = false
    end

    if vendorSettings.markCompletedThings == nil then
        vendorSettings.markCompletedThings = false
    end

    if vendorSettings.showMerchantCheckmarks == nil then
        vendorSettings.showMerchantCheckmarks = false
    end

    if vendorSettings.showVendorCheckmarks == nil then
        vendorSettings.showVendorCheckmarks = false
    end

    if vendorSettings.hideCollectedBossDrops == nil then
        vendorSettings.hideCollectedBossDrops = false
    end

    vendorSettings.openAchievementFrame = vendorSettings.openAchievementFrame ~= false

    dbDV = dbDV or {}
    dbDV.minimap = dbDV.minimap or {}
    dbDV.minimap.hide = not vendorSettings.showMinimapButton

    dv.currentTab = dv.currentTab or "vendors"
end

-------------------------------------------------
-- Minimap / LDB
-------------------------------------------------

local function RegisterMinimapButton()
    if not LibDBIcon then
        return
    end

    local ldb = LibStub:GetLibrary("LibDataBroker-1.1", true)

    if not ldb then
        return
    end

    local dataobj =
        ldb:NewDataObject(
        "DecorVendor",
        {
            type = "launcher",
            icon = "Interface\\AddOns\\DecorVendor\\Assets\\decorvendoricon.tga",
            label = "DecorVendor",
            text = "DecorVendor",
            name = "DecorVendor",
            OnClick = function(_, button)
                if button == "LeftButton" then
                    if frame and frame:IsShown() then
                        frame:Hide()
                    else
                        if dv.OpenMainUI then
                            dv.OpenMainUI()
                        else
                            if BuildVendorUI then
                                BuildVendorUI()
                            elseif dv.BuildVendorUI then
                                dv.BuildVendorUI()
                            end

                            if frame then
                                frame:Show()
                            end

                            if dv.ShowWelcomePanel then
                                dv:ShowWelcomePanel()
                            end
                        end
                    end
                elseif button == "RightButton" then
                    if frame and frame:IsShown() then
                        frame:Hide()
                    end

                    if Settings and dv.optionsCategory then
                        Settings.OpenToCategory(dv.optionsCategory:GetID())
                    end
                end
            end
        }
    )

    function dataobj:OnTooltipShow()
        self:AddLine("|cffffffffDecor Vendor|r")
        self:AddLine("|cff00ff00<Left Click>|r Toggle window")
        self:AddLine("|cff00ff00<Right Click>|r Settings")
    end

    LibDBIcon:Register("DecorVendor", dataobj, dbDV.minimap)

    if vendorSettings.showMinimapButton then
        LibDBIcon:Show("DecorVendor")
    else
        LibDBIcon:Hide("DecorVendor")
    end
end


-------------------------------------------------
-- Events
-------------------------------------------------

local init = CreateFrame("Frame")

init:RegisterEvent("ADDON_LOADED")
init:RegisterEvent("PLAYER_ENTERING_WORLD")
init:RegisterEvent("MERCHANT_SHOW")
init:RegisterEvent("HOUSING_MARKET_AVAILABILITY_UPDATED")
init:RegisterEvent("ACHIEVEMENT_EARNED")
init:RegisterEvent("QUEST_TURNED_IN")
init:RegisterEvent("HOUSE_DECOR_ADDED_TO_CHEST")

init:SetScript("OnEvent", function(self, event, loadedAddon, ...)
    if event == "ADDON_LOADED" and loadedAddon == addonName then
        InitDefaults()

        if UpdateEscBehavior then
            UpdateEscBehavior()
        end

        if dv.BuildProfessionLookup then
            dv.BuildProfessionLookup()
        end

        RegisterMinimapButton()

        vendorSettings.scale = vendorSettings.scale or 1.0
		frame:SetScale(vendorSettings.scale)

        if CreateOptionsPanel then
            CreateOptionsPanel()
        elseif dv.CreateOptionsPanel then
            dv.CreateOptionsPanel()
        end

        if UpdateSidebarForTab then
            UpdateSidebarForTab()
        end

        return
    end

    if event == "PLAYER_ENTERING_WORLD" then
        dv.catalogReady = false

        C_Timer.After(1, function()
            dv.catalogReady = true

            dv.decorIdToItemId = {}

            for itemID, data in pairs(dv.ActiveItems or {}) do
                if data.decorID then
                    dv.decorIdToItemId[data.decorID] = itemID
                end
            end

            wipe(vendorSessionCache)
            dv.collectionCache = {}

            if BuildVendorUI then
                BuildVendorUI()
            elseif dv.BuildVendorUI then
                dv.BuildVendorUI()
            end

            if HookMerchantFrame then
                HookMerchantFrame()
            elseif dv.HookMerchantFrame then
                dv.HookMerchantFrame()
            end
			
			if dv.PreloadGalleryAddon then
				dv.PreloadGalleryAddon()
			end
        end)

        return
    end

    if event == "MERCHANT_SHOW" then
        dv.waitingForMarketData = true

        if C_HousingCatalog and C_HousingCatalog.RequestHousingMarketInfoRefresh then
            C_HousingCatalog.RequestHousingMarketInfoRefresh()
        end

        return
    end

    if event == "HOUSING_MARKET_AVAILABILITY_UPDATED" then
        if dv.waitingForMarketData then
            dv.waitingForMarketData = false
            dv.catalogReady = true

            wipe(vendorSessionCache)
            dv.collectionCache = {}

            if BuildVendorUI then
                BuildVendorUI()
            elseif dv.BuildVendorUI then
                dv.BuildVendorUI()
            end
        end

        return
    end

    if event == "ACHIEVEMENT_EARNED" or event == "QUEST_TURNED_IN" then
        C_Timer.After(0.5, function()
            if BuildVendorUI then
                BuildVendorUI()
            elseif dv.BuildVendorUI then
                dv.BuildVendorUI()
            end
        end)

        return
    end

    if event == "HOUSE_DECOR_ADDED_TO_CHEST" then
        if not dv.catalogReady then
            return
        end

        local decorID = ...
        local itemID = dv.decorIdToItemId and dv.decorIdToItemId[decorID]

        if not itemID then
            return
        end

        local itemData = dv.ActiveItems and dv.ActiveItems[itemID]
        local noxp = itemData and itemData.noxp

        if noxp then
            vendorSettings.completedDropNoXP[itemID] = true
        else
            vendorSettings.completedDrop[itemID] = true
        end

        wipe(vendorSessionCache)

        if BuildVendorUI then
            BuildVendorUI()
        elseif dv.BuildVendorUI then
            dv.BuildVendorUI()
        end
    end
end)