local addonName, ns = ...

ns.upgradeVendorOpen = false

ns.SLOT_IDS = {
    { slot = 1,  name = "Head",      anchor = "TOPLEFT",  x = 24,  y = -78  },
    { slot = 2,  name = "Neck",      anchor = "TOPLEFT",  x = 24,  y = -118 },
    { slot = 3,  name = "Shoulder",  anchor = "TOPLEFT",  x = 24,  y = -158 },
    { slot = 15, name = "Back",      anchor = "TOPLEFT",  x = 24,  y = -198 },
    { slot = 5,  name = "Chest",     anchor = "TOPLEFT",  x = 24,  y = -238 },
    { slot = 9,  name = "Wrist",     anchor = "TOPLEFT",  x = 24,  y = -278 },
    { slot = 10, name = "Hands",     anchor = "TOPRIGHT", x = -24, y = -78  },
    { slot = 6,  name = "Waist",     anchor = "TOPRIGHT", x = -24, y = -118 },
    { slot = 7,  name = "Legs",      anchor = "TOPRIGHT", x = -24, y = -158 },
    { slot = 8,  name = "Feet",      anchor = "TOPRIGHT", x = -24, y = -198 },
    { slot = 11, name = "Ring 1",    anchor = "TOPRIGHT", x = -24, y = -238 },
    { slot = 12, name = "Ring 2",    anchor = "TOPRIGHT", x = -24, y = -278 },
    { slot = 13, name = "Trinket 1", anchor = "TOPLEFT",  x = 24,  y = -318 },
    { slot = 14, name = "Trinket 2", anchor = "TOPRIGHT", x = -24, y = -318 },
    { slot = 16, name = "Main Hand", anchor = "BOTTOMLEFT",  x = 80,  y = 60   },
    { slot = 17, name = "Off Hand",  anchor = "BOTTOMRIGHT", x = -80, y = 60   },
}

------------------------------------------------------------
-- Hidden tooltip for scanning upgrade track info
------------------------------------------------------------
local upgradeScanTooltip = CreateFrame("GameTooltip", "YYHUpgradeScanTooltip", nil, "GameTooltipTemplate")
upgradeScanTooltip:SetOwner(WorldFrame, "ANCHOR_NONE")

-- Cache tooltip scan results; invalidated on UNIT_INVENTORY_CHANGED
local scanCache = {}
function ns:InvalidateScanCache()
    wipe(scanCache)
end

local function ScanUpgradeTrack(slotID)
    -- Return cached result if available
    if scanCache[slotID] then
        return scanCache[slotID].track, scanCache[slotID].rank, scanCache[slotID].maxRank
    end
    upgradeScanTooltip:ClearLines()
    local ok = pcall(upgradeScanTooltip.SetInventoryItem, upgradeScanTooltip, "player", slotID)
    if not ok then return nil, nil, nil end

    for i = 1, upgradeScanTooltip:NumLines() do
        local line = _G["YYHUpgradeScanTooltipTextLeft" .. i]
        if line then
            local text = line:GetText() or ""
            -- Match "Upgrade Level: Champion 3/5" or similar
            local trackName, currRank, maxRank = text:match("Upgrade Level:%s+(%S+)%s+(%d+)/(%d+)")
            if trackName then
                local r, m = tonumber(currRank), tonumber(maxRank)
                scanCache[slotID] = { track = trackName, rank = r, maxRank = m }
                return trackName, r, m
            end
        end
    end
    scanCache[slotID] = { track = nil, rank = nil, maxRank = nil }
    return nil, nil, nil
end

-- Returns item info for an equipment slot
function ns:GetSlotInfo(slotID)
    local itemLink = GetInventoryItemLink("player", slotID)
    if not itemLink then
        return nil
    end

    local icon = GetInventoryItemTexture("player", slotID)
    local itemLevel = 0
    local itemQuality = 1

    -- Try multiple APIs for item level
    local itemLocation = ItemLocation:CreateFromEquipmentSlot(slotID)
    if C_Item.DoesItemExist(itemLocation) then
        local ok, lvl = pcall(C_Item.GetCurrentItemLevel, itemLocation)
        if ok and lvl then
            itemLevel = lvl
        end
        local ok2, qual = pcall(C_Item.GetItemQuality, itemLocation)
        if ok2 and qual then
            itemQuality = qual
        end
    end

    -- Fallback to GetDetailedItemLevelInfo
    if itemLevel == 0 then
        local ok, lvl = pcall(GetDetailedItemLevelInfo, itemLink)
        if ok and lvl then itemLevel = lvl end
    end

    -- Scan tooltip for actual upgrade track
    local trackName, currRank, maxRank = ScanUpgradeTrack(slotID)

    return {
        link = itemLink,
        ilvl = itemLevel,
        quality = itemQuality,
        icon = icon,
        track = trackName,
        rank = currRank,
        maxRank = maxRank,
    }
end

-- Check if an item can be upgraded
-- Returns: canUpgrade (bool), upgradeInfo table { currUpgrade, maxUpgrade, track, currIlvl, maxIlvl }
function ns:CanUpgradeItem(slotID)
    local info = ns:GetSlotInfo(slotID)
    if not info then return false, nil end

    local ilvl = info.ilvl
    if not ilvl or ilvl == 0 then return false, nil end

    local track, rank, maxRank

    -- Use tooltip-scanned track if available (accurate, handles ilvl overlaps)
    if info.track and ns.GEAR_TRACKS[info.track] then
        track = info.track
        rank = info.rank
        maxRank = info.maxRank
    else
        -- Fallback: guess from ilvl
        track = ns:GetTrackFromIlvl(ilvl)
        if not track then return false, nil end
        rank, maxRank = ns:GetRankInTrack(track, ilvl)

        -- If we can't find the exact rank, estimate it
        if not rank then
            local levels = ns.GEAR_TRACKS[track]
            if levels then
                for i, lvl in ipairs(levels) do
                    if ilvl <= lvl then
                        rank = i
                        break
                    end
                end
                rank = rank or #levels
                maxRank = #levels
            end
        end
    end

    if not rank or not maxRank then return false, nil end

    local maxIlvl = ns:GetMaxIlvlForTrack(track)
    local canUpgrade = rank < maxRank

    return canUpgrade, {
        currUpgrade = rank,
        maxUpgrade = maxRank,
        track = track,
        currIlvl = ilvl,
        maxIlvl = maxIlvl,
    }
end

-- Send an equipped item directly into the upgrade window
function ns:SendItemToUpgrade(slotID)
    if not ns.upgradeVendorOpen then
        print("|cff00ff00YippYapp Helper|r: Upgrade vendor is not open.")
        return
    end

    local itemLocation = ItemLocation:CreateFromEquipmentSlot(slotID)
    if not C_Item.DoesItemExist(itemLocation) then return end

    if C_ItemUpgrade and C_ItemUpgrade.SetItemUpgradeFromLocation then
        C_ItemUpgrade.SetItemUpgradeFromLocation(itemLocation)
    else
        ClearCursor()
        PickupInventoryItem(slotID)
        if ItemUpgradeFrame and ItemUpgradeFrame.ItemSlot then
            ItemUpgradeFrame.ItemSlot:Click()
        elseif ItemUpgradeFrame then
            local slot = ItemUpgradeFrame.LeftItemFrame or ItemUpgradeFrame.ItemButton
            if slot then
                slot:Click()
            end
        end
        ClearCursor()
    end
end

-- Anchor the helper frame relative to upgrade vendor or free-floating
function ns:AnchorFrame()
    local f = ns.MainFrame
    if not f then return end

    f:ClearAllPoints()

    if ns.upgradeVendorOpen and ItemUpgradeFrame and ItemUpgradeFrame:IsShown() then
        f:SetPoint("TOPLEFT", ItemUpgradeFrame, "TOPRIGHT", 2, 0)
    else
        f:SetPoint("CENTER")
    end
end

------------------------------------------------------------
-- Initialization & Events
------------------------------------------------------------
local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("ADDON_LOADED")
eventFrame:RegisterEvent("PLAYER_INTERACTION_MANAGER_FRAME_SHOW")
eventFrame:RegisterEvent("PLAYER_INTERACTION_MANAGER_FRAME_HIDE")
eventFrame:RegisterEvent("CURRENCY_DISPLAY_UPDATE")
eventFrame:RegisterEvent("UNIT_INVENTORY_CHANGED")

local ITEM_UPGRADE_INTERACTION = Enum.PlayerInteractionType.ItemUpgrade
local characterFrameHooked = false

eventFrame:SetScript("OnEvent", function(self, event, arg1)
    if event == "ADDON_LOADED" and arg1 == addonName then
        YippYappHelperDB = YippYappHelperDB or {}

        -- Restore previous raid scan (with type validation)
        if type(YippYappHelperDB.raidInspect) == "table" then
            ns.RaidInspectData = YippYappHelperDB.raidInspect
        end

        -- Validate discounts table
        if YippYappHelperDB.discounts and type(YippYappHelperDB.discounts) ~= "table" then
            YippYappHelperDB.discounts = nil
        end

        print("|cff00ff00YippYapp Helper|r loaded — type |cff00ff00/yh|r to toggle")

        -- Hook CharacterFrame OnShow so we can suppress it during upgrade vendor
        if CharacterFrame and not characterFrameHooked then
            CharacterFrame:HookScript("OnShow", function()
                if ns.upgradeVendorOpen then
                    HideUIPanel(CharacterFrame)
                end
            end)
            characterFrameHooked = true
        end

    elseif event == "PLAYER_INTERACTION_MANAGER_FRAME_SHOW" and arg1 == ITEM_UPGRADE_INTERACTION then
        ns.upgradeVendorOpen = true

        -- Hide if already showing
        if CharacterFrame and CharacterFrame:IsShown() then
            HideUIPanel(CharacterFrame)
        end

        if ns.MainFrame then
            ns:RefreshAllSlots()
            ns:RefreshCrests()
            ns:AnchorFrame()
            ns.MainFrame:Show()
        end

    elseif event == "PLAYER_INTERACTION_MANAGER_FRAME_HIDE" and arg1 == ITEM_UPGRADE_INTERACTION then
        ns.upgradeVendorOpen = false
        if ns.MainFrame then
            ns.MainFrame:Hide()
        end

    elseif event == "UNIT_INVENTORY_CHANGED" and arg1 == "player" then
        -- Invalidate tooltip cache when gear changes
        ns:InvalidateScanCache()
        if ns.MainFrame and ns.MainFrame:IsShown() then
            ns:RefreshCrests()
            ns:RefreshAllSlots()
        end
    elseif event == "CURRENCY_DISPLAY_UPDATE" then
        if ns.MainFrame and ns.MainFrame:IsShown() then
            ns:RefreshCrests()
            ns:RefreshAllSlots()
        end
    end
end)

SLASH_YIPPYAPPHELPER1 = "/yh"
SLASH_YIPPYAPPHELPER2 = "/yippyapp"
SlashCmdList["YIPPYAPPHELPER"] = function(msg)
    msg = strtrim(msg or "")
    local cmd, arg = strsplit(" ", msg, 2)
    cmd = strlower(cmd or "")

    -- /yh help
    if cmd == "help" then
        print("|cff00ff00=== YippYapp Helper ===|r")
        print("  /yh — open dashboard")
        print("  /yh raid — scan raid/party for tier pieces")
        print("  /yh profile — show/set player profile")
        print("  /yh profile <name> — set profile (casual, heroic_raider, mythic_raider, mplus_mid, mplus_high, alt)")
        print("  /yh discount <track> — toggle crest discount for a track (adventurer, veteran, champion, hero, myth)")
        print("  /yh discounts — show current discount status")
        print("  /yh debug — dump slot data to chat")
        return
    end

    -- /yh raid
    if cmd == "raid" then
        if ns.RaidFrame and ns.RaidFrame:IsShown() then
            ns.RaidFrame:Hide()
        else
            ns:ScanRaid()
        end
        return
    end

    -- /yh profile [name]
    if cmd == "profile" then
        if arg and strtrim(arg) ~= "" then
            local profileId = strlower(strtrim(arg))
            local found = false
            for _, profile in ipairs(ns.PROFILES) do
                if profile.id == profileId then
                    YippYappHelperDB.profile = profileId
                    print("|cff00ff00YippYapp Helper|r: Profile set to |cffffffff" .. profile.name .. "|r")
                    found = true
                    break
                end
            end
            if not found then
                print("|cff00ff00YippYapp Helper|r: Unknown profile. Options:")
                for _, p in ipairs(ns.PROFILES) do
                    print("  " .. p.id .. " — " .. p.name)
                end
            else
                -- Refresh if window is open
                if ns.MainFrame and ns.MainFrame:IsShown() then
                    ns:RefreshAllSlots()
                    ns:RefreshCrests()
                end
            end
        else
            local current = ns:GetCurrentProfile()
            print("|cff00ff00YippYapp Helper|r: Current profile: |cffffffff" .. current.name .. "|r")
            print("  Spend freely: " .. table.concat(current.freeCrests, ", "))
            print("  Precious: " .. table.concat(current.preciousCrests, ", "))
            print("Available profiles:")
            for _, p in ipairs(ns.PROFILES) do
                local marker = p.id == current.id and " |cff00ff00(active)|r" or ""
                print("  " .. p.id .. " — " .. p.name .. marker)
            end
        end
        return
    end

    -- /yh discount <track>
    if cmd == "discount" then
        if not arg or strtrim(arg) == "" then
            print("|cff00ff00YippYapp Helper|r: Usage: /yh discount <track>")
            print("  Tracks: adventurer, veteran, champion, hero, myth")
            return
        end
        local trackName = strtrim(arg)
        -- Capitalize first letter
        trackName = trackName:sub(1,1):upper() .. trackName:sub(2):lower()

        if not ns.GEAR_TRACKS[trackName] then
            print("|cff00ff00YippYapp Helper|r: Unknown track '" .. trackName .. "'")
            return
        end

        YippYappHelperDB.discounts = YippYappHelperDB.discounts or {}
        if YippYappHelperDB.discounts[trackName] then
            YippYappHelperDB.discounts[trackName] = nil
            print("|cff00ff00YippYapp Helper|r: " .. trackName .. " discount |cffff0000removed|r (20 crests per upgrade)")
        else
            YippYappHelperDB.discounts[trackName] = true
            print("|cff00ff00YippYapp Helper|r: " .. trackName .. " discount |cff00ff00enabled|r (10 crests per upgrade)")
        end

        if ns.MainFrame and ns.MainFrame:IsShown() then
            ns:RefreshAllSlots()
        end
        return
    end

    -- /yh discounts
    if cmd == "discounts" then
        print("|cff00ff00=== Crest Costs ===|r")
        for _, trackName in ipairs(ns.TRACK_ORDER) do
            local cost = ns:GetCrestCost(trackName)
            local hasAchieve = ns:HasDiscountAchievement(trackName)
            local db = YippYappHelperDB or {}
            local manualOverride = db.discounts and db.discounts[trackName]
            local source = ""
            if hasAchieve then
                source = " (achievement: " .. trackName .. " of the Dawn)"
            elseif manualOverride then
                source = " (manual override)"
            end
            local discounted = cost == ns.DISCOUNTED_CREST_COST
            local status = discounted
                and "|cff00ff0010 per rank|r" .. source
                or "20 per rank"
            print("  " .. trackName .. ": " .. status)
        end
        print("Use /yh discount <track> to manually toggle discounts")
        return
    end

    -- /yh debug
    if cmd == "debug" then
        print("|cff00ff00=== YippYapp Debug ===|r")
        local profile = ns:GetCurrentProfile()
        print("Profile: " .. profile.name)
        print("Free crests: " .. table.concat(profile.freeCrests, ", "))
        print("Precious crests: " .. table.concat(profile.preciousCrests, ", "))
        for _, trackName in ipairs(ns.TRACK_ORDER) do
            local count = ns:GetCrestCountByTrack(trackName)
            local cost = ns:GetCrestCost(trackName)
            print("  " .. trackName .. ": " .. count .. " crests, " .. cost .. " per upgrade, " .. ns:GetAffordableUpgrades(trackName) .. " upgrades affordable")
        end
        print("--- Equipped Slots ---")
        for _, slotInfo in ipairs(ns.SLOT_IDS) do
            local itemLink = GetInventoryItemLink("player", slotInfo.slot)
            if itemLink then
                local info = ns:GetSlotInfo(slotInfo.slot)
                local canUp, upInfo = ns:CanUpgradeItem(slotInfo.slot)
                local rec, reason = ns:GetRecommendation(slotInfo.slot)
                local upStr = "no data"
                if upInfo then
                    upStr = upInfo.track .. " " .. upInfo.currUpgrade .. "/" .. upInfo.maxUpgrade .. " (ilvl " .. upInfo.currIlvl .. "->" .. upInfo.maxIlvl .. ")"
                end
                local risk = ns:GetReplacementRisk(slotInfo.slot, info.ilvl)
                print(string.format("  %s: %s | risk: %s | %s | %s",
                    slotInfo.name, upStr, risk, rec.label, reason))
            end
        end
        return
    end

    -- Default: toggle dashboard
    if ns.ToggleDashboard then
        ns:ToggleDashboard()
    end
end
