local addonName, ns = ...
local Fatebound = ns

-- ===============================
-- Inventory Storage
-- ===============================
Fatebound.Inventory = Fatebound.Inventory or {}

-- --------------------------
-- Layout Config
-- --------------------------
local COLUMNS = 6
local ROWS = 5
local ICON_SIZE = 38
local PADDING = 10
local GRID_X_OFFSET = -50
local GRID_Y_OFFSET = -12

-- ==========================================================
-- INVENTORY WINDOW
-- ==========================================================
function Fatebound.Inventory:ShowInventory(parentFrame)
    local parent = parentFrame or UIParent

    if not self.frame then
        self.frame = CreateFrame("Frame", "FateboundInventoryFrame", parent)
        self.frame:SetSize(556, 290)
        self.frame:SetPoint("RIGHT", parent, "RIGHT", 488, -55)
        self.frame:SetFrameStrata("LOW")

        -- ----------------------
        -- STATS PANEL
        -- ----------------------
        self.statsPanel = CreateFrame("Frame", nil, self.frame)
        self.statsPanel:SetSize(150, 200)
        self.statsPanel:SetPoint("LEFT", self.frame, "RIGHT", -180, 0)

        -- ----------------------
        -- CORRUPTION
        -- ----------------------
        self.statsPanel.corruptionText = self.statsPanel:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        self.statsPanel.corruptionText:SetPoint("TOPLEFT", self.statsPanel, "TOPLEFT", 10, 12)
        self.statsPanel.corruptionText:SetScript("OnEnter", function(fs)
            GameTooltip:SetOwner(fs, "ANCHOR_RIGHT")
            GameTooltip:AddLine("Corruption", 1, 1, 1, true)
            GameTooltip:AddLine("Represents the total accumulated corruption from all your stats combined.", nil, nil, nil, true)
            GameTooltip:Show()
        end)
        self.statsPanel.corruptionText:SetScript("OnLeave", GameTooltip_Hide)

        -- ----------------------
        -- INDIVIDUAL STATS
        -- ----------------------
        local statNames = Fatebound.STAT_LIST
        local statDescriptions = {
            Madness    = "Your mind frays under the gaze of the Old Gods, causing unpredictable phenomena to manifest around you.",
            Despair    = "This might do something.",
            Obsession  = "Your fixations resonate with the Old Gods, unnaturally preserving their favor and slowing its decay.",
            Dominance  = "Your ruthless might bends the souls of the vanquished, leaving behind relics twisted by your corrupting influence.",
            Convergence    = "The chaos within you twists fortune to your favor, increasing the chance of successful item upgrades."
        }

        self.statsPanel.statTexts = {}
        for i, stat in ipairs(statNames) do
            local statText = self.statsPanel:CreateFontString(nil, "OVERLAY", "GameFontNormal")
            statText:SetPoint("TOPLEFT", self.statsPanel, "TOPLEFT", 10, -40 - (i-1)*20)
            self.statsPanel.statTexts[stat] = statText

            statText:SetScript("OnEnter", function(fs)
                GameTooltip:SetOwner(fs, "ANCHOR_RIGHT")
                GameTooltip:AddLine("|cFFFFFFFF" .. stat .. "|r", nil, nil, nil, true)
                GameTooltip:AddLine(statDescriptions[stat], nil, nil, nil, true)
                GameTooltip:Show()
            end)
            statText:SetScript("OnLeave", GameTooltip_Hide)
        end

        -- ----------------------
        -- SOUL ESSENCE
        -- ----------------------
        self.statsPanel.soulText = self.statsPanel:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        self.statsPanel.soulText:SetPoint("BOTTOMLEFT", self.statsPanel, "BOTTOMLEFT", 10, -12)
        self.statsPanel.soulText:SetScript("OnEnter", function(fs)
            GameTooltip:SetOwner(fs, "ANCHOR_RIGHT")
            GameTooltip:AddLine("Soul Essence", 1, 1, 1, true)
            GameTooltip:AddLine("Total: " .. Fatebound.FormatWithCommas(FateboundDB.SoulEssence or 0), nil, nil, nil, true)
            GameTooltip:Show()
        end)
        self.statsPanel.soulText:SetScript("OnLeave", GameTooltip_Hide)

        -- ----------------------
        -- BACKGROUND
        -- ----------------------
        local bg = self.frame:CreateTexture(nil, "BACKGROUND")
        bg:SetTexture("interface/garrison/adventuremissionsboardmaw")
        bg:SetTexCoord(0.0009765625, 0.5439453125, 0.2861328125, 0.5693359375)
        bg:SetAllPoints()

        self:CreateSlots()
        self.frame:Show()
        Fatebound:RefreshAll()
        return
    end

    if self.frame:IsShown() then
        self.frame:Hide()
    else
        self.frame:Show()
        Fatebound:RefreshAll()
    end
end

-- ==========================================================
-- Update Stats Panel
-- ==========================================================
function Fatebound.Inventory:UpdateStatsPanel()
    if not self.statsPanel then return end

    local soul = FateboundDB.SoulEssence or 0
    local active = (FateboundDB.favor or 0) > 0

    -- Update stats text
    local corruptionColor = active and "|cFFFFFFFF" or "|cffbb2f2a"
    self.statsPanel.corruptionText:SetText(
        "Corruption: " .. corruptionColor .. string.format("%.2f", FateboundDB.stats.Corruption or 0) .. "|r"
    )

    for stat, text in pairs(self.statsPanel.statTexts) do
        local color = active and "|cFFFFFFFF" or "|cffbb2f2a"
        text:SetText(stat .. ": " .. color .. (FateboundDB.stats[stat] or 0) .. "|r")
    end

    self.statsPanel.soulText:SetText("Soul Essence: |cFFFFFFFF" .. Fatebound.FormatNumber(soul) .. "|r")
end

-- ===============================
-- Cursor Item
-- ===============================
Fatebound.Inventory.CursorItem = nil
local cursorFrame

local function CreateInventoryCursor()
    cursorFrame = CreateFrame("Frame", nil, UIParent)
    cursorFrame:SetSize(ICON_SIZE, ICON_SIZE)
    cursorFrame:SetFrameStrata("TOOLTIP")
    cursorFrame.texture = cursorFrame:CreateTexture(nil, "ARTWORK")
    cursorFrame.texture:SetAllPoints()
    cursorFrame:Hide()

    cursorFrame:SetScript("OnUpdate", function()
        if Fatebound.Inventory.CursorItem then
            local x, y = GetCursorPosition()
            local scale = UIParent:GetEffectiveScale()
            cursorFrame:SetPoint("CENTER", UIParent, "BOTTOMLEFT", x/scale, y/scale)
            cursorFrame:Show()
        else
            cursorFrame:Hide()
            cursorFrame.texture:SetTexture(nil)
        end
    end)
end
CreateInventoryCursor()

-- ===============================
-- Inventory slot click handler
-- ===============================
local function SlotOnClick(slotIndex, button)
    local slotItem = Fatebound.Inventory.Items[slotIndex]

    if button == "RightButton" and Fatebound.Inventory.CursorItem then
        if Fatebound.Inventory.CursorItem.originalIndex then
            Fatebound.Inventory.Items[Fatebound.Inventory.CursorItem.originalIndex] = Fatebound.Inventory.CursorItem.item
        end
        Fatebound.Inventory.CursorItem = nil
        cursorFrame:Hide()
        Fatebound:RefreshAll()
        return
    end

    if Fatebound.Inventory.CursorItem then
        if not slotItem then
            Fatebound.Inventory.Items[slotIndex] = Fatebound.Inventory.CursorItem.item
        else
            Fatebound.Inventory.Items[Fatebound.Inventory.CursorItem.originalIndex] = slotItem
            Fatebound.Inventory.Items[slotIndex] = Fatebound.Inventory.CursorItem.item
        end

        Fatebound.Inventory.CursorItem = nil
        cursorFrame:Hide()
        Fatebound:RefreshAll()
        return
    end

    if slotItem and button == "LeftButton" then
        Fatebound.Inventory.CursorItem = { item = slotItem, originalIndex = slotIndex }
        Fatebound.Inventory.Items[slotIndex] = nil
        cursorFrame.texture:SetTexture(slotItem.icon or "Interface/ICONS/INV_Misc_QuestionMark")
        cursorFrame:Show()
        Fatebound:RefreshAll()
    end
end

-- ===============================
-- Inventory slot creation
-- ===============================
function Fatebound.Inventory:CreateSlots()
    if self.slots then return end
    self.slots = {}

    local gridWidth = (COLUMNS * ICON_SIZE) + ((COLUMNS - 1) * PADDING)
    local startX = -gridWidth / 2 + GRID_X_OFFSET
    local startY = -PADDING + GRID_Y_OFFSET

    for row = 0, ROWS - 1 do
        for col = 0, COLUMNS - 1 do
            local index = row * COLUMNS + col + 1
            local slot = CreateFrame("Frame", nil, self.frame)
            slot:SetSize(56, 56)
            slot:SetPoint("TOP", self.frame, "TOP",
                startX + col * (ICON_SIZE + PADDING) + ICON_SIZE / 2,
                startY - row * (ICON_SIZE + PADDING)
            )

            slot.bg = slot:CreateTexture(nil, "BACKGROUND")
            slot.bg:SetTexture("interface/hud/uiwowlabsactionbar")
            slot.bg:SetTexCoord(0.95263671875, 0.99365234375, 0.09228515625, 0.13330078125)
            slot.bg:SetAllPoints()

            slot.border = slot:CreateTexture(nil, "OVERLAY")
            slot.border:SetTexture("interface/hud/uiwowlabsactionbar")
            slot.border:SetTexCoord(0.95263671875, 0.99365234375, 0.13720703125, 0.17822265625)
            slot.border:SetPoint("CENTER")
            slot.border:SetSize(56, 56)
            slot.border:SetVertexColor(0.7, 0.7, 0.7)

            slot.icon = slot:CreateTexture(nil, "ARTWORK")
            slot.icon:SetDrawLayer("ARTWORK", 2)
            slot.icon:Hide()

            slot:SetScript("OnMouseUp", function(_, button)
                SlotOnClick(index, button)
            end)

            self.slots[index] = slot
        end
    end
end

-- ===============================
-- Shared Item Tooltip Function
-- ===============================
local TREE_NAMES = {
    yshaarj = "Y'Shaarj",
    nzoth   = "N'Zoth",
    cthun   = "C'Thun",
    yogg    = "Yogg-Saron",
    ghuun   = "G'huun",
    any     = "the Old Gods",
}

function ns.ShowItemTooltip(frame, item)
    if not item then return end

    GameTooltip:SetOwner(frame, "ANCHOR_RIGHT")
    GameTooltip:ClearLines()

    -- Elite icon inline
    local eliteIcon = ""
    if item.isElite then
        eliteIcon = "|TInterface/Minimap/ObjectIconsAtlas:24:24:0:0:1024:1024:1:69:131:199|t "
    end

    GameTooltip:SetText(eliteIcon .. item.name)

    local treeName = TREE_NAMES[item.tree] or "Unknown"
    GameTooltip:AddLine("|cffe6cc80Relic of " .. treeName .. "|r")
    GameTooltip:AddLine("|cff00ccffRank " .. (item.rank or 1) .. "|r")
    GameTooltip:AddLine(" ")

    if item.stats then
        if item.stats.Corruption then
            GameTooltip:AddLine("+" .. item.stats.Corruption .. "% Corruption", 0.01, 1, 0.01)
        end

        for stat, value in pairs(item.stats) do
            if stat ~= "Corruption" then
                GameTooltip:AddLine("+" .. value .. " " .. stat, 1, 1, 1)
            end
        end
    end

    if item.lore then
        GameTooltip:AddLine(" ")
        GameTooltip:AddLine('"' .. item.lore .. '"')
    end

	-- ======================================================
	-- MAX WIDTH + WRAP + FIX HEIGHT OVERFLOW
	-- ======================================================
	local maxWidth = 380

	GameTooltip:Show()

	if GameTooltip:GetWidth() > maxWidth then
		GameTooltip:SetWidth(maxWidth)

		for i = 1, GameTooltip:NumLines() do
			local left = _G["GameTooltipTextLeft" .. i]
			if left then
				left:SetWidth(maxWidth - 20)
			end

			local right = _G["GameTooltipTextRight" .. i]
			if right then
				right:SetWidth(maxWidth - 20)
			end
		end

		GameTooltip:Show()
	end
end

-- ==========================================================
-- UPDATE DISPLAY
-- ==========================================================
function Fatebound.Inventory:UpdateDisplay()
    if not self.frame then return end

    for i, slot in ipairs(self.slots) do
        local item = self.Items[i]

        if item then
            -- Set the icon
            slot.icon:SetTexture(item.icon or "Interface/ICONS/INV_Misc_QuestionMark")
            slot.icon:SetSize(ICON_SIZE, ICON_SIZE)
            slot.icon:SetPoint("CENTER")
            slot.icon:Show()

            -- Tooltip
            slot:SetScript("OnEnter", function()
                ns.ShowItemTooltip(slot, item)
            end)
            slot:SetScript("OnLeave", GameTooltip_Hide)
        else
            slot.icon:Hide()
            slot:SetScript("OnEnter", nil)
            slot:SetScript("OnLeave", nil)
        end
    end
end

-- ==========================================================
-- ADD ITEM (FORGE EXTRACTION)
-- ==========================================================
function Fatebound.Inventory:AddItem(item)
    if not item then return false end   -- return false if item is nil

    local maxSlots = COLUMNS * ROWS
    for i = 1, maxSlots do
        if not self.Items[i] then
            self.Items[i] = item
            Fatebound:RefreshAll()
            return true
        end
    end

    UIErrorsFrame:AddMessage("Inventory full.", 1, 0, 0)
    return false
end
