local _, ns = ...
local L = ns.L or {}

local UIData = ns.UIData or {}
local WISHLIST_FILTERS = UIData.WISHLIST_FILTERS or {}

local UIJournalView = ns.UIJournalView or {}
local buildWishlistEntriesForCharacter = UIJournalView.BuildWishlistEntriesForCharacter or function()
    return {}, { total = 0, raids = 0, dungeons = 0 }
end
local buildWishlistEntryMeta = UIJournalView.BuildWishlistEntryMeta or function()
    return ""
end

local UIWishlistCard = {}
ns.UIWishlistCard = UIWishlistCard

local function createWishlistCard(parent, helpers)
    local createSectionFrame = helpers.createSectionFrame
    local createMiniActionButton = helpers.createMiniActionButton
    local createLabel = helpers.createLabel
    local createSubTab = helpers.createSubTab
    local styleScrollFrame = helpers.styleScrollFrame

    local card = createSectionFrame(parent, "card")
    card:Hide()

    card.closeButton = createMiniActionButton(card, L.CLOSE or "Close", 68)
    card.closeButton:SetPoint("TOPRIGHT", -14, -16)

    card.title = createLabel(card, "GameFontNormalLarge", "LEFT")
    card.title:SetPoint("TOPLEFT", 14, -18)
    card.title:SetPoint("TOPRIGHT", card.closeButton, "TOPLEFT", -12, 0)
    card.title:SetText(L.WISHLIST_TITLE or "Wishlist")

    card.subtitle = createLabel(card, "GameFontHighlightSmall", "LEFT")
    card.subtitle:SetPoint("TOPLEFT", card.title, "BOTTOMLEFT", 0, -8)
    card.subtitle:SetPoint("TOPRIGHT", card.closeButton, "BOTTOMLEFT", -12, 0)
    card.subtitle:SetText(L.WISHLIST_SUBTITLE or "All wishlisted loot for the selected character across raids and dungeons.")

    card.summary = createLabel(card, "GameFontHighlightSmall", "LEFT")
    card.summary:SetPoint("TOPLEFT", card.subtitle, "BOTTOMLEFT", 0, -12)
    card.summary:SetPoint("TOPRIGHT", -14, 0)

    card.breakdown = createLabel(card, "GameFontDisableSmall", "LEFT")
    card.breakdown:SetPoint("TOPLEFT", card.summary, "BOTTOMLEFT", 0, -6)
    card.breakdown:SetPoint("TOPRIGHT", -14, 0)

    card.filterBar = CreateFrame("Frame", nil, card)
    card.filterBar:SetPoint("TOPLEFT", card.breakdown, "BOTTOMLEFT", 0, -14)
    card.filterBar:SetPoint("TOPRIGHT", -14, 0)
    card.filterBar:SetHeight(24)

    card.filterButtons = {}
    for index, filterData in ipairs(WISHLIST_FILTERS) do
        local button = createSubTab(card.filterBar, filterData.label(), 98)
        if index == 1 then
            button:SetPoint("LEFT", 0, 0)
        else
            button:SetPoint("LEFT", card.filterButtons[index - 1], "RIGHT", 8, 0)
        end
        button.filterKey = filterData.key
        card.filterButtons[index] = button
    end

    card.scroll = CreateFrame("ScrollFrame", nil, card, "UIPanelScrollFrameTemplate")
    card.scroll:SetPoint("TOPLEFT", card.filterBar, "BOTTOMLEFT", 0, -14)
    card.scroll:SetPoint("BOTTOMRIGHT", -26, 14)

    card.scrollChild = CreateFrame("Frame", nil, card.scroll)
    card.scrollChild:SetSize(720, 10)
    card.scroll:SetScrollChild(card.scrollChild)
    styleScrollFrame(card.scroll)

    card.emptyText = createLabel(card.scrollChild, "GameFontDisableLarge", "LEFT")
    card.emptyText:SetPoint("TOPLEFT", 14, -12)
    card.emptyText:SetPoint("TOPRIGHT", -14, -12)
    card.emptyText:SetJustifyV("TOP")
    card.emptyText:SetWordWrap(true)
    card.emptyText:SetText(L.WISHLIST_EMPTY or "No wishlisted items yet. Use the tracker icon on loot rows to add items here.")

    card.rows = {}

    return card
end

local function ensureWishlistRows(ui, count, helpers)
    while #ui.frame.wishlistCard.rows < count do
        local row = helpers.createRaidJournalLootRow(ui.frame.wishlistCard.scrollChild)
        local index = #ui.frame.wishlistCard.rows + 1
        row:SetPoint("TOPLEFT", 14, -12 - ((index - 1) * 68))
        row:SetPoint("TOPRIGHT", -14, -12 - ((index - 1) * 68))
        ui.frame.wishlistCard.rows[index] = row
    end
end

local function refreshWishlistButton(ui, character, helpers)
    if not ui.frame or not ui.frame.wishlistButton then
        return
    end

    local counts = (character and character.key and ns.GetRaidLootTrackerCounts)
        and ns:GetRaidLootTrackerCounts(character.key)
        or { wish = 0, obtained = 0 }

    helpers.setMiniActionButtonActive(ui.frame.wishlistButton, ui.wishlistPanelOpen == true)
    if ui.frame.wishlistButton.SetActive then
        ui.frame.wishlistButton:SetActive(ui.wishlistPanelOpen == true)
        ui.frame.wishlistButton:Enable()
    end
    ui.frame.wishlistButton:SetAlpha(((tonumber(counts.wish) or 0) > 0 or ui.wishlistPanelOpen) and 1 or 0.90)
end

local function refreshWishlistCard(ui, character, helpers)
    if not ui.frame or not ui.frame.wishlistCard then
        return
    end

    local card = ui.frame.wishlistCard
    local filterKey = ui.wishlistFilterKey or "all"
    local entries, counts = buildWishlistEntriesForCharacter(character, filterKey)
    local trackerCounts = (character and character.key and ns.GetRaidLootTrackerCounts)
        and ns:GetRaidLootTrackerCounts(character.key)
        or { wish = 0, obtained = 0 }
    local scrollWidth = math.floor(card.scroll:GetWidth() or 0)
    if scrollWidth <= 0 then
        scrollWidth = math.floor((card:GetWidth() or 0) - 54)
    end
    scrollWidth = math.max(320, scrollWidth)

    card.title:SetText(L.WISHLIST_TITLE or "Wishlist")
    card.subtitle:SetText(L.WISHLIST_SUBTITLE or "All wishlisted loot for the selected character across raids and dungeons.")
    card.summary:SetText(string.format(
        L.WISHLIST_SUMMARY_CHARACTER or "%d wishlisted items for %s-%s",
        counts.total or 0,
        (character and character.name) or (L.UNKNOWN or "Unknown"),
        (character and character.realm) or (L.UNKNOWN or "Unknown")
    ))
    card.breakdown:SetText(string.format(
        L.WISHLIST_SUMMARY_BREAKDOWN or "Raids %d  |  Dungeons %d",
        counts.raids or 0,
        counts.dungeons or 0
    ))

    for _, button in ipairs(card.filterButtons or {}) do
        if button.SetActive then
            button:SetActive((button.filterKey or "all") == filterKey)
        end
    end

    ensureWishlistRows(ui, #entries, helpers)

    local rowCount = 0
    for index, row in ipairs(card.rows or {}) do
        local entry = entries[index]
        if entry then
            rowCount = rowCount + 1
            row:Show()
            row.characterKey = character and character.key or nil
            row.characterName = character and character.name or nil
            row.difficultyKey = entry.difficultyKey or "normal"
            row.wishlistSources = entry.sources
            helpers.applyRaidLootRow(row, entry.loot)
            row.meta:SetText(buildWishlistEntryMeta(entry))
        else
            row.wishlistSources = nil
            row:Hide()
        end
    end

    card.scrollChild:SetWidth(scrollWidth)

    card.emptyText:ClearAllPoints()
    card.emptyText:SetPoint("TOPLEFT", 14, -12)
    card.emptyText:SetPoint("TOPRIGHT", -14, -12)
    card.emptyText:SetShown(#entries == 0)
    card.emptyText:SetText(
        (#entries == 0 and ((trackerCounts.wish or 0) == 0))
            and (L.WISHLIST_EMPTY or "No wishlisted items yet. Use the tracker icon on loot rows to add items here.")
            or (L.WISHLIST_EMPTY_FILTER or "No wishlisted items found for this filter.")
    )

    card.scrollChild:SetHeight(math.max(10, 16 + (rowCount * 68), (#entries == 0 and 120 or 0)))
end

UIWishlistCard.CreateCard = createWishlistCard
UIWishlistCard.EnsureRows = ensureWishlistRows
UIWishlistCard.RefreshButton = refreshWishlistButton
UIWishlistCard.RefreshCard = refreshWishlistCard
