-- VDS_Rows_Herb
-- ============================================================================
-- vds-redux pattern: lazy-build per kind + explicit cross-kind hide on each
-- bind. Handles BOTH `kind = "herb"` (data row) AND `kind = "herbHeader"`
-- (section header like "Salvage in BLACK pigment recipe for BLACK dye").
--
-- Herb columns (donor parity): name (left) | expansion abbr | AH price | cart count.

VDS = VDS or {}

local FW     = VDS.Constants.FLOATING_WIDGET
local C      = VDS.Constants.COLOR_CODE
local C_GOLD = C.warn
local C_DIM  = C.dim

local function lazyBuildHerbRowChrome(row)
    if row._vdsHerbBuilt then return end
    row._vdsHerbBuilt = true

    -- Name (left).
    local nameText = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    nameText:SetPoint("LEFT", 8, 0)
    nameText:SetWidth(140)
    nameText:SetJustifyH("LEFT")
    nameText:SetWordWrap(false)
    row._herbNameText = nameText

    local midText = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")  -- expansion abbr; 50->40 for dye-icon strip
    midText:SetPoint("LEFT", nameText, "RIGHT", 4, 0)
    midText:SetWidth(40)
    midText:SetJustifyH("LEFT")
    row._herbMidText = midText

    -- AH price (rightmost; per-row cart-count removed when Stock tab became sole cart workflow).
    local priceText = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    priceText:SetPoint("RIGHT", row, "RIGHT", -8, 0)
    priceText:SetWidth(50)
    priceText:SetJustifyH("RIGHT")
    row._herbPrice = priceText

    -- Dye-icon strip: which dyes this herb contributes to. Buttons (not Textures)
    -- so per-icon hover fires; up to 12, left-to-right after the xpac column.
    row._herbDyeIcons = row._herbDyeIcons or {}
    for i = 1, 12 do
        local b = _G.CreateFrame("Frame", nil, row)
        b:SetSize(14, 14)
        if i == 1 then
            b:SetPoint("LEFT", midText, "RIGHT", 6, 0)
        else
            b:SetPoint("LEFT", row._herbDyeIcons[i - 1], "RIGHT", 2, 0)
        end
        local tex = b:CreateTexture(nil, "ARTWORK")
        tex:SetAllPoints()
        b._tex = tex
        b:EnableMouse(true)
        VDS.TooltipEngine:Attach(b, VDS.TooltipRecipes.HerbDyeIcon)
        b:Hide()
        row._herbDyeIcons[i] = b
    end

    local headerLabel = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")  -- herbHeader kind
    headerLabel:SetPoint("LEFT",  row, "LEFT",  8, 0)
    headerLabel:SetPoint("RIGHT", row, "RIGHT", -8, 0)
    headerLabel:SetJustifyH("LEFT")
    headerLabel:SetJustifyV("MIDDLE")
    VDS.Theme:Register(headerLabel, "TextRowHeader")
    headerLabel:Hide()
    row._herbHeaderLabel = headerLabel

    local headerBg = row:CreateTexture(nil, "BACKGROUND", nil, 1)
    headerBg:SetAllPoints()
    headerBg:SetTexture("Interface\\Buttons\\WHITE8x8")
    VDS.Theme:Register(headerBg, "RowHeaderBg")
    headerBg:Hide()
    row._herbHeaderBg = headerBg

    if not row._herbHl then
        local hl = row:CreateTexture(nil, "HIGHLIGHT")
        hl:SetAllPoints()
        hl:SetTexture("Interface\\Buttons\\WHITE8x8")
        VDS.Theme:Register(hl, "RowHoverHl")
        row._herbHl = hl
    end

    row:RegisterForClicks("AnyUp")
    if not row:GetScript("OnClick") then
        row:SetScript("OnClick", function(self, button)
            if not VDS.Controller_Browse then return end
            if self._lsRowKind == "dye" then
                VDS.Controller_Browse:OnDyeRowClick(self, button)
            elseif self._lsRowKind == "herb" then
                VDS.Controller_Browse:OnHerbRowClick(self, button)
            end
            -- herbHeader rows: no-op (non-interactive section divider).
        end)
    end

    if not row:GetScript("OnEnter") then  -- shared with Rows_Dye; branches on _lsRowKind
        VDS.Rows_Dye_attachHover(row)
    end
end

local function hideDyeChrome(row)
    if row._swatch     then row._swatch:Hide()     end
    if row._gloss      then row._gloss:Hide()      end
    if row._selectedBg then row._selectedBg:Hide() end
    if row._selAccent  then row._selAccent:Hide()  end
    if row._nameText   then row._nameText:Hide()   end
    if row._countText  then row._countText:Hide()  end
    -- Dyes-tab gold cost ("40g") -- leftover overlaps the herb's own price
    -- column on Dyes -> Herbs tab switches if not hidden.
    if row._priceText  then row._priceText:Hide() end
    -- Must also hide dye SECTION HEADER chrome; without this the old "RED 7 dyes"
    -- FontString stays visible and causes the "Star Moss / BlSavage" overlap
    -- on Dyes -> Herbs tab switches.
    if row._headerBg    then row._headerBg:Hide()    end
    if row._headerLabel then row._headerLabel:Hide() end
    if row._headerCount then row._headerCount:Hide() end
end

local function bindHerbRow(row, data)
    lazyBuildHerbRowChrome(row)
    -- (cross-pool hideDyeChrome call removed: dye and herb tabs now use
    -- separate scrollBoxes, so this Button can only ever be a herbRow.)

    if data.kind == "herbHeader" then
        row._lsRowKind = "herbHeader"
        row._herbID    = nil
        row._dyeID     = nil
        -- Must match extent calculator (20); recycled dye-row stays 36 tall
        -- and overflows 16px into next slot -- that's the "Star Moss / BlSavage" source.
        row:SetHeight(20)

        -- Hide data-row chrome; show header chrome.
        row._herbNameText:Hide()
        row._herbMidText:Hide()
        row._herbPrice:Hide()
        for _, b in ipairs(row._herbDyeIcons or {}) do b:Hide() end

        row._herbHeaderBg:Show()
        row._herbHeaderLabel:Show()
        local count = data.count and (" |cff7a7a7a(" .. data.count .. " herbs)|r") or ""
        row._herbHeaderLabel:SetText((data.label or "") .. count)
        return
    end

    row._lsRowKind = "herb"
    row._herbID    = data.herbID
    row._dyeID     = nil
    row:SetHeight(FW.DYE_HERB_ROW_HEIGHT + 2)  -- must match extent calculator (23)

    row._herbHeaderBg:Hide()
    row._herbHeaderLabel:Hide()

    -- Async name kick lives in widget config (resolveAsync); BindingEngine
    -- middleware handles the Request + dedup. Row factory just paints.
    if data.herbID then
        VDS.Log:Debug("items", string.format("[6] herb-row id=%d paint name='%s'",
            data.herbID, tostring(data.name)))
    end
    row._herbNameText:SetText(data.name or RETRIEVING_DATA)
    if not row._herbNameText._lsRegistered then
        VDS.Theme:Register(row._herbNameText, "TextRowName")
        row._herbNameText._lsRegistered = true
    end
    row._herbNameText:Show()

    if data.expIdx then
        local exp = VDS.StaticData.GetHerbExpansion(data.expIdx)
        if exp then
            row._herbMidText:SetText(exp.abbr or "")
            local col = exp.color
            row._herbMidText:SetTextColor(col[1], col[2], col[3], 1)
        else
            row._herbMidText:SetText("")
        end
    else
        row._herbMidText:SetText("")
    end
    row._herbMidText:Show()

    if data.price then
        local pretty = VDS.StaticData.FormatGold(data.price)
        row._herbPrice:SetText(pretty and (C_GOLD .. pretty .. "|r") or "")
    else
        row._herbPrice:SetText(C_DIM .. "--|r")
    end
    row._herbPrice:Show()

    local ids = data.dyeItemIDs or {}
    for i, b in ipairs(row._herbDyeIcons) do
        local itemID = ids[i]
        if itemID then
            local icon = _G.C_Item.GetItemIconByID(itemID)
            if icon then
                b._tex:SetTexture(icon)
                b._itemID = itemID
                b:Show()
            else
                b:Hide()
                b._itemID = nil
            end
        else
            b:Hide()
            b._itemID = nil
        end
    end
end

local function resetHerbRow(row)
    row._herbID = nil
    if row._herbNameText    then row._herbNameText:SetText("")    end
    if row._herbMidText     then row._herbMidText:SetText("")     end
    if row._herbPrice       then row._herbPrice:SetText("")       end
    if row._herbHeaderLabel then row._herbHeaderLabel:SetText("") end
    for _, b in ipairs(row._herbDyeIcons or {}) do
        b:Hide()
        b._itemID = nil
    end
end

VDS.RowRegistry:Register("herbRow", {
    init  = bindHerbRow,
    reset = resetHerbRow,
})
