local addonName, privateDB = ...

-- ============================================================================
-- DATA TAB MODULE
-- Crafting history and Farming history/statistics
-- ============================================================================

local CONFIG = privateDB.CONFIG
local L = HDG_L or {}  -- Localization
local HDG_DataTab = {}
privateDB.HDG_DataTab = HDG_DataTab

local mainFrame = nil
local dataFrame = nil

-- Reference to lumber types
local LUMBER_TYPES = nil

-- Spell ID to recipe lookup cache
local spellToRecipe = nil
-- Item ID to recipe lookup cache
local itemToRecipe = nil
-- Decor ID to recipe lookup cache
local decorToRecipe = nil

-- Build spell ID -> recipe lookup table
local function BuildSpellToRecipeLookup()
    if spellToRecipe then return spellToRecipe end
    spellToRecipe = {}
    if HDG_DecorDB then
        for _, recipe in pairs(HDG_DecorDB) do
            if recipe.spellID then
                spellToRecipe[recipe.spellID] = recipe
            end
        end
    end
    return spellToRecipe
end

-- Build item ID -> recipe lookup table
local function BuildItemToRecipeLookup()
    if itemToRecipe then return itemToRecipe end
    itemToRecipe = {}
    if HDG_DecorDB then
        for _, recipe in pairs(HDG_DecorDB) do
            if recipe.itemID then
                itemToRecipe[recipe.itemID] = recipe
            end
        end
    end
    return itemToRecipe
end

-- Build decor ID -> recipe lookup table
local function BuildDecorToRecipeLookup()
    if decorToRecipe then return decorToRecipe end
    decorToRecipe = {}
    if HDG_DecorDB then
        for _, recipe in pairs(HDG_DecorDB) do
            if recipe.decorID then
                decorToRecipe[recipe.decorID] = recipe
            end
        end
    end
    return decorToRecipe
end

-- ============================================================================
-- CRAFTING HISTORY FUNCTIONS
-- ============================================================================

-- Format timestamp for display
function HDG_DataTab.FormatTimestamp(timestamp)
    if not timestamp then return "Unknown" end
    return date("%Y-%m-%d %H:%M", timestamp)
end

-- Get crafting history from settings
function HDG_DataTab.GetCraftingHistory()
    local settings = _G.HDG_Settings
    if settings and settings.craftingHistory then
        return settings.craftingHistory
    end
    return {}
end

-- Clear crafting history
function HDG_DataTab.ClearCraftingHistory()
    local settings = _G.HDG_Settings
    if settings then
        settings.craftingHistory = {}
        print("|cFF00FF00[Housing Decor Guide]|r Crafting history cleared.")
    end
end

-- Export crafting history to CSV format (copies to clipboard via edit box)
function HDG_DataTab.ExportCraftingToCSV()
    local history = HDG_DataTab.GetCraftingHistory()
    if #history == 0 then
        print("|cFFFF6666[Housing Decor Guide]|r No crafting history to export.")
        return nil
    end

    -- Build CSV string
    local lines = {}
    table.insert(lines, "Timestamp,Item,ItemID,Quantity,Profession,Source,Character,Realm,ItemPrice,MaterialCost,PriceSource")

    for _, entry in ipairs(history) do
        local timestamp = entry.timestamp and date("%Y-%m-%d %H:%M:%S", entry.timestamp) or ""
        -- Use localized item name for export
        local fallbackName = entry.name or entry.itemName or "Unknown"
        local localizedName = entry.itemID and HDG_Data.GetLocalizedName(entry.itemID, fallbackName) or fallbackName
        local itemName = localizedName:gsub(",", ";")  -- Escape commas
        local itemID = entry.itemID or ""
        local quantity = entry.quantity or entry.count or 1
        local profession = (entry.profession or ""):gsub(",", ";")
        local source = entry.source or "Crafted"
        local character = (entry.character or ""):gsub(",", ";")
        local realm = (entry.realm or ""):gsub(",", ";")
        local itemPrice = entry.itemPrice or ""
        local materialCost = entry.materialCost or ""
        local priceSource = entry.priceSource or ""

        table.insert(lines, string.format("%s,%s,%s,%d,%s,%s,%s,%s,%s,%s,%s",
            timestamp, itemName, itemID, quantity, profession, source, character, realm, itemPrice, materialCost, priceSource))
    end

    return table.concat(lines, "\n")
end

-- Log a craft if the spellID corresponds to a decor recipe (legacy method)
function HDG_DataTab.LogCraftIfDecor(spellID)
    if not spellID then return end

    local lookup = BuildSpellToRecipeLookup()
    local recipe = lookup[spellID]

    if recipe then
        -- This is a decor recipe craft!
        local settings = _G.HDG_Settings
        if not settings then return end

        settings.craftingHistory = settings.craftingHistory or {}

        -- Add to history (newest first, limit to 100 entries)
        local charName = UnitName("player")
        local realmName = GetRealmName()
        table.insert(settings.craftingHistory, 1, {
            itemID = recipe.itemID,
            itemName = recipe.name,
            spellID = spellID,
            timestamp = time(),
            profession = recipe.profession,
            character = charName,
            realm = realmName,
        })

        -- Trim to 100 entries
        while #settings.craftingHistory > 100 do
            table.remove(settings.craftingHistory)
        end
    end
end

-- Log a craft from item link (new method using TRADE_SKILL_ITEM_CRAFTED_RESULT)
function HDG_DataTab.LogCraftFromItemLink(itemLink, quantity)
    if not itemLink then return end

    -- Extract itemID from item link: |cff...|Hitem:ITEMID:...|h[Name]|h|r
    local itemID = tonumber(itemLink:match("item:(%d+)"))
    if not itemID then return end

    local lookup = BuildItemToRecipeLookup()
    local recipe = lookup[itemID]

    if recipe then
        -- This is a decor recipe craft!
        local settings = _G.HDG_Settings
        if not settings then return end

        settings.craftingHistory = settings.craftingHistory or {}

        -- Get prices at time of crafting (if price addon available)
        local itemPrice = nil      -- Market price of the crafted decor item
        local materialCost = nil   -- Total cost of all reagents
        local priceSource = nil
        if HDG_PriceIntegration then
            -- Get market price of the crafted item
            if HDG_PriceIntegration.GetItemPrice then
                local price, source = HDG_PriceIntegration.GetItemPrice(recipe.itemID)
                if price and price > 0 then
                    itemPrice = price
                    priceSource = source
                end
            end
            -- Get total material cost
            if recipe.reagents and HDG_PriceIntegration.CalculateTotalPrice then
                local totalPrice = HDG_PriceIntegration.CalculateTotalPrice(recipe.reagents)
                if totalPrice and totalPrice > 0 then
                    materialCost = totalPrice
                    -- Set priceSource if not already set
                    if not priceSource then
                        local _, source = HDG_PriceIntegration.HasPriceAddon()
                        priceSource = source
                    end
                end
            end
        end

        -- Add to history (newest first, limit to 100 entries)
        local charName = UnitName("player")
        local realmName = GetRealmName()
        table.insert(settings.craftingHistory, 1, {
            itemID = recipe.itemID,
            itemName = recipe.name,
            quantity = quantity or 1,
            timestamp = time(),
            profession = recipe.profession,
            character = charName,
            realm = realmName,
            itemPrice = itemPrice,        -- market price in copper at time of craft
            materialCost = materialCost,  -- total reagent cost in copper at time of craft
            priceSource = priceSource,    -- "TSM" or "Auctionator"
            source = "Crafted",           -- acquisition source (Crafted vs Learned)
        })

        -- Trim to 100 entries
        while #settings.craftingHistory > 100 do
            table.remove(settings.craftingHistory)
        end

        -- Refresh history display if Data tab is visible
        if mainFrame and mainFrame.RefreshHistoryList then
            mainFrame.RefreshHistoryList()
        end
    end
end

-- Log acquisition when player learns a decor item from bags
function HDG_DataTab.LogAcquisition(decorID)
    if not decorID then return end

    -- Look up item info from Blizzard API
    if not C_HousingCatalog or not C_HousingCatalog.GetCatalogEntryInfoByRecordID then return end
    local info = C_HousingCatalog.GetCatalogEntryInfoByRecordID(1, decorID, true)
    if not info then return end

    local settings = _G.HDG_Settings
    if not settings then return end
    settings.craftingHistory = settings.craftingHistory or {}

    local charName = UnitName("player")
    local realmName = GetRealmName()

    table.insert(settings.craftingHistory, 1, {
        decorID = decorID,
        itemID = info.itemID,  -- May be nil for non-item decor
        itemName = info.name,
        timestamp = time(),
        character = charName,
        realm = realmName,
        source = "Learned",  -- Distinguishes from crafted items
    })

    -- Trim to 100 entries
    while #settings.craftingHistory > 100 do
        table.remove(settings.craftingHistory)
    end

    -- Trigger craft quote for acquired decor items (only if master toggle and chattiness > 0)
    local quotesEnabled = settings.quotesEnabled
    if quotesEnabled == nil then quotesEnabled = true end
    local chattiness = settings.vamooseChattiness or 30
    if quotesEnabled and settings.craftQuotesEnabled ~= false and chattiness > 0 then
        local lookup = BuildDecorToRecipeLookup()
        local recipe = lookup[decorID]
        if recipe and recipe.profession and recipe.expansion then
            -- Get expansion abbreviation (e.g., "Classic Alchemy" -> "Classic")
            local expansionAbbr = HDG_ExpansionData.GetAbbreviation(recipe.expansion)

            -- Get quote for this profession/expansion combo
            local HDG_CraftQuotes = privateDB.HDG_CraftQuotes
            local HDG_Vamoose = privateDB.HDG_Vamoose
            if HDG_CraftQuotes and HDG_Vamoose then
                local quote = HDG_CraftQuotes.GetRandomQuote(recipe.profession, expansionAbbr)
                if quote then
                    local speaker = HDG_CraftQuotes.GetSpeaker(recipe.profession)
                    if speaker then
                        local onlyChat = settings.quotesOnlyChat or false
                        -- Show talking head unless "only chat" is enabled
                        if not onlyChat then
                            HDG_Vamoose.PlayTalkingHead(quote, recipe.profession, speaker.displayID)
                        end
                        -- Print to chat if "only chat" is enabled
                        if onlyChat then
                            print(string.format("|cFF14b8a6[%s]|r %s", speaker.name, quote))
                        end
                    end
                end
            end
        end
    end

    -- Refresh history display if Data tab is visible
    if mainFrame and mainFrame.RefreshHistoryList then
        mainFrame.RefreshHistoryList()
    end
end

-- ============================================================================
-- FARMING HISTORY FUNCTIONS
-- ============================================================================

-- Initialize farming history in SavedVariables if needed
function HDG_DataTab.InitFarmingHistory()
    if not _G.HDG_Settings then
        _G.HDG_Settings = {}
    end
    if not _G.HDG_Settings.farmingHistory then
        _G.HDG_Settings.farmingHistory = {}
    end
end

-- Get farming history from settings
function HDG_DataTab.GetFarmingHistory()
    HDG_DataTab.InitFarmingHistory()
    return _G.HDG_Settings.farmingHistory
end

-- Save or update a farming session in history (upsert behavior)
-- sessionData: { sessionId, lumberId, lumberName, collected, duration, perHour, zone, timestamp }
-- sessionId is used to update an existing session rather than creating a new one
function HDG_DataTab.SaveFarmingSession(sessionData)
    HDG_DataTab.InitFarmingHistory()

    local history = _G.HDG_Settings.farmingHistory
    local sessionId = sessionData.sessionId

    -- If we have a sessionId, try to find and update the existing entry
    if sessionId then
        for i, entry in ipairs(history) do
            if entry.sessionId == sessionId then
                -- Update existing entry (including zone for multi-zone sessions)
                entry.collected = sessionData.collected or entry.collected
                entry.duration = sessionData.duration or entry.duration
                entry.perHour = sessionData.perHour or entry.perHour
                entry.timestamp = sessionData.timestamp or entry.timestamp
                entry.zone = sessionData.zone or entry.zone  -- Update zone to current location
                return entry
            end
        end
    end

    -- No existing entry found, create new one
    local entry = {
        sessionId = sessionId or (sessionData.lumberId .. "_" .. time()),
        timestamp = sessionData.timestamp or time(),
        lumberId = sessionData.lumberId,
        lumberName = sessionData.lumberName,
        collected = sessionData.collected or 0,
        duration = sessionData.duration or 0,  -- in seconds
        perHour = sessionData.perHour or 0,
        zone = sessionData.zone or "Unknown",
        character = sessionData.character,
        realm = sessionData.realm
    }

    -- Insert at beginning (newest first)
    table.insert(history, 1, entry)

    -- Keep only last 100 entries
    while #history > 100 do
        table.remove(history)
    end

    return entry
end

-- Clear farming history
function HDG_DataTab.ClearFarmingHistory()
    if _G.HDG_Settings then
        _G.HDG_Settings.farmingHistory = {}
        print("|cFF00FF00[Housing Decor Guide]|r Farming history cleared.")
        -- Refresh display if visible
        if dataFrame and dataFrame:IsVisible() then
            HDG_DataTab.RefreshFarmingDisplay()
        end
    end
end

-- Export farming history to CSV format
function HDG_DataTab.ExportFarmingToCSV()
    local history = HDG_DataTab.GetFarmingHistory()
    if #history == 0 then
        print("|cFFFF6666[Housing Decor Guide]|r No farming history to export.")
        return nil
    end

    -- Build CSV string
    local lines = {}
    table.insert(lines, "Timestamp,Lumber,LumberID,Collected,Rate/Hour,Duration(sec),Zone,Character,Realm")

    for _, entry in ipairs(history) do
        local timestamp = entry.timestamp and date("%Y-%m-%d %H:%M:%S", entry.timestamp) or ""
        -- Use localized lumber name for export
        local localizedName = HDG_ExpansionData.GetLumberMaterialName(entry.lumberId) or entry.lumberName or "Unknown"
        local lumberName = localizedName:gsub(",", ";")  -- Escape commas
        local lumberId = entry.lumberId or ""
        local collected = entry.collected or 0
        local perHour = string.format("%.1f", entry.perHour or 0)
        local duration = math.floor(entry.duration or 0)
        local zone = (entry.zone or "Unknown"):gsub(",", ";")
        local character = (entry.character or ""):gsub(",", ";")
        local realm = (entry.realm or ""):gsub(",", ";")

        table.insert(lines, string.format("%s,%s,%s,%d,%s,%d,%s,%s,%s",
            timestamp, lumberName, lumberId, collected, perHour, duration, zone, character, realm))
    end

    return table.concat(lines, "\n")
end

-- Format duration for display (seconds -> "Xh Ym" or "Xm Ys")
local function FormatDuration(seconds)
    if not seconds or seconds <= 0 then return "0s" end

    if seconds < 60 then
        return string.format("%ds", math.floor(seconds))
    elseif seconds < 3600 then
        local mins = math.floor(seconds / 60)
        local secs = math.floor(seconds % 60)
        return string.format("%dm %ds", mins, secs)
    else
        local hours = math.floor(seconds / 3600)
        local mins = math.floor((seconds % 3600) / 60)
        return string.format("%dh %dm", hours, mins)
    end
end

-- FormatTimestamp is now defined above in CRAFTING HISTORY FUNCTIONS section

-- ============================================================================
-- UI CREATION
-- ============================================================================

function HDG_DataTab.Init(frame)
    mainFrame = frame
    LUMBER_TYPES = HDG_ExpansionData and HDG_ExpansionData.LUMBER_TYPES or {}
end

function HDG_DataTab.CreatePanel()
    if not mainFrame then return end

    dataFrame = CreateFrame("Frame", nil, mainFrame, "BackdropTemplate")
    dataFrame:SetPoint("TOPLEFT", CONFIG.SPACING.PANEL_PADDING, -(CONFIG.BANNER_HEIGHT + CONFIG.TAB_HEIGHT + 8))
    dataFrame:SetSize(CONFIG.MAIN_FRAME_WIDTH - (CONFIG.SPACING.PANEL_PADDING * 2), CONFIG.PANEL_HEIGHT)
    dataFrame:SetBackdrop({
        bgFile = CONFIG.TEXTURES.WHITE_BG,
        edgeFile = CONFIG.TEXTURES.WHITE_BG,
        tile = false,
        edgeSize = 1,
        insets = { left = 0, right = 0, top = 0, bottom = 0 }
    })
    dataFrame:SetBackdropColor(unpack(CONFIG.COLORS.PANEL_BG))
    dataFrame:SetBackdropBorderColor(unpack(HDG_UIHelpers.BORDER_COLOR))
    dataFrame:Hide()
    mainFrame.dataFrame = dataFrame

    -- Create scrollable content frame for the entire tab
    local scrollFrame = CreateFrame("ScrollFrame", nil, dataFrame, "UIPanelScrollFrameTemplate")
    scrollFrame:SetPoint("TOPLEFT", 8, -8)
    scrollFrame:SetPoint("BOTTOMRIGHT", -28, 8)

    local scrollChild = CreateFrame("Frame", nil, scrollFrame)
    scrollFrame:SetScrollChild(scrollChild)
    scrollChild:SetWidth(CONFIG.MAIN_FRAME_WIDTH - 60)
    scrollChild:SetHeight(1200)
    dataFrame.scrollChild = scrollChild

    -- Apply minimalist scrollbar styling
    if HDG_UIHelpers and HDG_UIHelpers.StyleScrollBar then
        HDG_UIHelpers.StyleScrollBar(scrollFrame)
    end

    local yOffset = 0

    -- ========================================================================
    -- CRAFTING HISTORY SECTION
    -- ========================================================================
    local craftingTitle = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    craftingTitle:SetPoint("TOPLEFT", 4, yOffset)
    craftingTitle:SetText("|cFFfcd34d" .. (L["HEADER_CRAFTING_HISTORY"] or "Decor Crafting / Acquisition History") .. "|r")

    -- Help text (next to title)
    local craftingDesc = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    craftingDesc:SetPoint("LEFT", craftingTitle, "RIGHT", 10, 0)
    craftingDesc:SetText("|cFF666666(click item to preview, headers to sort)|r")

    -- Export CSV Button for crafting
    local craftExportBtn = CreateFrame("Button", nil, scrollChild)
    craftExportBtn:SetSize(100, 22)
    craftExportBtn:SetPoint("TOPRIGHT", -4, yOffset)
    local craftExportTex = craftExportBtn:CreateTexture(nil, "ARTWORK")
    craftExportTex:SetAllPoints()
    craftExportTex:SetTexture(CONFIG.ADDON_TEXTURES.CSV_EXPORT)
    craftExportBtn:SetScript("OnEnter", function() craftExportTex:SetAlpha(0.8) end)
    craftExportBtn:SetScript("OnLeave", function() craftExportTex:SetAlpha(1.0) end)

    craftExportBtn:SetScript("OnClick", function()
        if HDG_DataTab.ExportCraftingToCSV then
            local csv = HDG_DataTab.ExportCraftingToCSV()
            if csv then
                -- Create a popup dialog with the CSV data for copying
                if not HDG_CraftExportFrame then
                    local f = CreateFrame("Frame", "HDG_CraftExportFrame", UIParent, "BackdropTemplate")
                    f:SetSize(500, 350)
                    f:SetPoint("CENTER")
                    f:SetBackdrop({
                        bgFile = "Interface\\Buttons\\WHITE8X8",
                        edgeFile = "Interface\\Buttons\\WHITE8X8",
                        tile = false, edgeSize = 2,
                        insets = { left = 0, right = 0, top = 0, bottom = 0 }
                    })
                    f:SetBackdropColor(0.1, 0.1, 0.12, 0.95)
                    f:SetBackdropBorderColor(0.08, 0.72, 0.65, 1)
                    f:SetFrameStrata("DIALOG")
                    f:SetMovable(true)
                    f:EnableMouse(true)
                    f:RegisterForDrag("LeftButton")
                    f:SetScript("OnDragStart", f.StartMoving)
                    f:SetScript("OnDragStop", f.StopMovingOrSizing)

                    local exportTitle = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
                    exportTitle:SetPoint("TOP", 0, -10)
                    exportTitle:SetText("|cFF14b8a6Export Crafting History|r")

                    local instr = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
                    instr:SetPoint("TOP", exportTitle, "BOTTOM", 0, -5)
                    instr:SetText("|cFF888888Select all (Ctrl+A) then copy (Ctrl+C)|r")

                    local sf = CreateFrame("ScrollFrame", nil, f, "UIPanelScrollFrameTemplate")
                    sf:SetPoint("TOPLEFT", 15, -50)
                    sf:SetPoint("BOTTOMRIGHT", -35, 45)

                    local eb = CreateFrame("EditBox", nil, sf)
                    eb:SetMultiLine(true)
                    eb:SetFontObject("GameFontHighlightSmall")
                    eb:SetWidth(440)
                    eb:SetAutoFocus(false)
                    eb:SetScript("OnEscapePressed", function(self) self:ClearFocus() end)
                    sf:SetScrollChild(eb)
                    f.editBox = eb

                    local closeBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
                    closeBtn:SetPoint("BOTTOM", 0, 10)
                    closeBtn:SetSize(80, 22)
                    closeBtn:SetText("Close")
                    closeBtn:SetScript("OnClick", function() f:Hide() end)

                    HDG_CraftExportFrame = f
                end

                HDG_CraftExportFrame.editBox:SetText(csv)
                HDG_CraftExportFrame.editBox:HighlightText()
                HDG_CraftExportFrame.editBox:SetFocus()
                HDG_CraftExportFrame:Show()
                print("|cFF14b8a6[Housing Decor Guide]|r Exported " .. #HDG_DataTab.GetCraftingHistory() .. " crafting entries.")
            end
        end
    end)

    yOffset = yOffset - 25

    -- Sorting state for crafting history
    local craftSortColumn = "timestamp"
    local craftSortAscending = false

    -- Column widths for crafting
    local COL_TIME = 110
    local COL_ITEM = 210
    local COL_PRICE = 70
    local COL_SOURCE = 55
    local COL_CHAR = 115

    -- Column header helper
    local function CreateColumnHeader(parent, text, width, xOffset, column, yPos)
        local btn = CreateFrame("Button", nil, parent)
        btn:SetSize(width, 18)
        btn:SetPoint("TOPLEFT", xOffset, yPos)

        local label = btn:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        label:SetPoint("LEFT", 2, 0)
        label:SetText("|cFFa0aec0" .. text .. "|r")
        btn.label = label

        local arrow = btn:CreateTexture(nil, "ARTWORK")
        arrow:SetSize(10, 10)
        arrow:SetPoint("LEFT", label, "RIGHT", 4, 0)
        arrow:SetTexture(CONFIG.ADDON_TEXTURES.SORT_ARROW)
        arrow:Hide()
        btn.arrow = arrow

        btn:SetScript("OnEnter", function(self)
            self.label:SetText("|cFFFFFFFF" .. text .. "|r")
        end)
        btn:SetScript("OnLeave", function(self)
            self.label:SetText("|cFFa0aec0" .. text .. "|r")
        end)

        btn.column = column
        return btn
    end

    -- Column headers for crafting
    local craftHeaderRow = CreateFrame("Frame", nil, scrollChild)
    craftHeaderRow:SetPoint("TOPLEFT", 4, yOffset)
    craftHeaderRow:SetSize(CONFIG.MAIN_FRAME_WIDTH - 80, 18)

    local craftHeaderBg = craftHeaderRow:CreateTexture(nil, "BACKGROUND")
    craftHeaderBg:SetAllPoints()
    craftHeaderBg:SetColorTexture(0.15, 0.15, 0.18, 1)

    local craftTimeHeader = CreateColumnHeader(craftHeaderRow, "Time", COL_TIME, 5, "timestamp", 0)
    local craftItemHeader = CreateColumnHeader(craftHeaderRow, "Item", COL_ITEM, 5 + COL_TIME, "itemName", 0)
    local craftPriceHeader = CreateColumnHeader(craftHeaderRow, "Price", COL_PRICE, 5 + COL_TIME + COL_ITEM, "itemPrice", 0)
    local craftSourceHeader = CreateColumnHeader(craftHeaderRow, "Source", COL_SOURCE, 5 + COL_TIME + COL_ITEM + COL_PRICE, "source", 0)
    local craftCharHeader = CreateColumnHeader(craftHeaderRow, "Character", COL_CHAR, 5 + COL_TIME + COL_ITEM + COL_PRICE + COL_SOURCE, "character", 0)

    yOffset = yOffset - 20

    -- Crafting history container
    local craftContainer = CreateFrame("Frame", nil, scrollChild, "BackdropTemplate")
    craftContainer:SetPoint("TOPLEFT", 4, yOffset)
    craftContainer:SetSize(CONFIG.MAIN_FRAME_WIDTH - 80, 150)
    craftContainer:SetBackdrop({
        bgFile = CONFIG.TEXTURES.WHITE_BG,
        edgeFile = CONFIG.TEXTURES.WHITE_BG,
        tile = false,
        edgeSize = 1,
        insets = { left = 0, right = 0, top = 0, bottom = 0 }
    })
    craftContainer:SetBackdropColor(0.08, 0.08, 0.10, 0.9)
    craftContainer:SetBackdropBorderColor(unpack(HDG_UIHelpers.BORDER_COLOR))

    -- Crafting history scroll frame
    local craftScrollFrame = CreateFrame("ScrollFrame", nil, craftContainer, "UIPanelScrollFrameTemplate")
    craftScrollFrame:SetPoint("TOPLEFT", 5, -5)
    craftScrollFrame:SetPoint("BOTTOMRIGHT", -25, 5)

    local craftScrollChild = CreateFrame("Frame", nil, craftScrollFrame)
    craftScrollFrame:SetScrollChild(craftScrollChild)
    craftScrollChild:SetWidth(CONFIG.MAIN_FRAME_WIDTH - 120)
    craftScrollChild:SetHeight(1)
    dataFrame.craftScrollChild = craftScrollChild

    if HDG_UIHelpers and HDG_UIHelpers.StyleScrollBar then
        HDG_UIHelpers.StyleScrollBar(craftScrollFrame)
    end

    -- Row pool for crafting history
    local craftRowPool = {}

    local function GetCraftRow(index)
        if craftRowPool[index] then
            return craftRowPool[index]
        end

        local row = CreateFrame("Frame", nil, craftScrollChild)
        row:SetSize(CONFIG.MAIN_FRAME_WIDTH - 130, 18)

        row.timeText = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        row.timeText:SetPoint("LEFT", 0, 0)
        row.timeText:SetWidth(COL_TIME)
        row.timeText:SetJustifyH("LEFT")

        row.itemBtn = CreateFrame("Button", nil, row)
        row.itemBtn:SetPoint("LEFT", COL_TIME, 0)
        row.itemBtn:SetSize(COL_ITEM, 18)

        row.itemText = row.itemBtn:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        row.itemText:SetPoint("LEFT", 0, 0)
        row.itemText:SetWidth(COL_ITEM - 5)
        row.itemText:SetJustifyH("LEFT")

        row.itemBtn:SetScript("OnEnter", function(self)
            if self.itemID or self.itemName then
                row.itemText:SetText("|cFF2dd4bf" .. (self.itemName or "Unknown") .. "|r")
                GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
                GameTooltip:SetText("Click to preview", 1, 1, 1)
                GameTooltip:Show()
            end
        end)
        row.itemBtn:SetScript("OnLeave", function(self)
            if self.itemID or self.itemName then
                row.itemText:SetText("|cFFFFFFFF" .. (self.itemName or "Unknown") .. "|r")
            end
            GameTooltip:Hide()
        end)
        row.itemBtn:SetScript("OnClick", function(self)
            if HDG_DecorPreview and HDG_DecorPreview.PreviewByName then
                -- Pass name, itemID, and decorID - PreviewByName will use what's available
                HDG_DecorPreview:PreviewByName(self.itemName, self.itemID, self.decorID)
            end
        end)

        row.priceBtn = CreateFrame("Button", nil, row)
        row.priceBtn:SetPoint("LEFT", COL_TIME + COL_ITEM, 0)
        row.priceBtn:SetSize(COL_PRICE, 18)

        row.priceText = row.priceBtn:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        row.priceText:SetPoint("LEFT", 0, 0)
        row.priceText:SetWidth(COL_PRICE)
        row.priceText:SetJustifyH("LEFT")

        row.priceBtn:SetScript("OnEnter", function(self)
            local parent = self:GetParent()
            if parent.materialCost or parent.itemPrice then
                GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
                GameTooltip:AddLine("AH Price at Time of Crafting", 1, 0.82, 0.3)
                if parent.itemPrice and parent.itemPrice > 0 then
                    local itemPriceStr = HDG_PriceIntegration and HDG_PriceIntegration.FormatGold(parent.itemPrice) or string.format("%dg", math.floor(parent.itemPrice / 10000))
                    GameTooltip:AddDoubleLine("Item Value:", itemPriceStr, 0.7, 0.7, 0.7, 0.08, 0.72, 0.65)
                end
                if parent.materialCost and parent.materialCost > 0 then
                    local matCostStr = HDG_PriceIntegration and HDG_PriceIntegration.FormatGold(parent.materialCost) or string.format("%dg", math.floor(parent.materialCost / 10000))
                    GameTooltip:AddDoubleLine("Material Cost:", matCostStr, 0.7, 0.7, 0.7, 1, 0.82, 0.3)
                end
                if parent.itemPrice and parent.itemPrice > 0 and parent.materialCost and parent.materialCost > 0 then
                    local profit = parent.itemPrice - parent.materialCost
                    local profitStr = HDG_PriceIntegration and HDG_PriceIntegration.FormatGold(math.abs(profit)) or string.format("%dg", math.floor(math.abs(profit) / 10000))
                    if profit >= 0 then
                        GameTooltip:AddDoubleLine("Profit:", profitStr, 0.7, 0.7, 0.7, 0.53, 1, 0.53)
                    else
                        GameTooltip:AddDoubleLine("Loss:", profitStr, 0.7, 0.7, 0.7, 1, 0.4, 0.4)
                    end
                end
                if parent.priceSource then
                    GameTooltip:AddLine(" ")
                    GameTooltip:AddLine("Source: " .. parent.priceSource, 0.5, 0.5, 0.5)
                end
                GameTooltip:Show()
            end
        end)
        row.priceBtn:SetScript("OnLeave", function() GameTooltip:Hide() end)

        row.sourceText = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        row.sourceText:SetPoint("LEFT", COL_TIME + COL_ITEM + COL_PRICE, 0)
        row.sourceText:SetWidth(COL_SOURCE)
        row.sourceText:SetJustifyH("LEFT")

        row.charText = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        row.charText:SetPoint("LEFT", COL_TIME + COL_ITEM + COL_PRICE + COL_SOURCE, 0)
        row.charText:SetWidth(COL_CHAR)
        row.charText:SetJustifyH("LEFT")

        craftRowPool[index] = row
        return row
    end

    -- Update sort arrows for crafting
    local function UpdateCraftSortArrows()
        local function SetArrowState(header, isActive)
            if isActive then
                header.arrow:Show()
                if craftSortAscending then
                    header.arrow:SetTexCoord(0, 1, 1, 0)
                else
                    header.arrow:SetTexCoord(0, 1, 0, 1)
                end
            else
                header.arrow:Hide()
            end
        end

        SetArrowState(craftTimeHeader, craftSortColumn == "timestamp")
        SetArrowState(craftItemHeader, craftSortColumn == "itemName")
        SetArrowState(craftPriceHeader, craftSortColumn == "itemPrice")
        SetArrowState(craftSourceHeader, craftSortColumn == "source")
        SetArrowState(craftCharHeader, craftSortColumn == "character")
    end

    -- Refresh crafting history list
    local function RefreshCraftingList()
        for _, row in pairs(craftRowPool) do
            row:Hide()
        end

        local HDG_ConfigTab = _G.HDG_ConfigTab
        if not HDG_ConfigTab then return end

        local history = HDG_DataTab.GetCraftingHistory()
        local historyYOffset = 0

        if #history == 0 then
            local row = GetCraftRow(1)
            row:SetPoint("TOPLEFT", 0, historyYOffset)
            row.timeText:SetText("")
            row.itemText:SetText("|cFF666666" .. (L["STATUS_NO_HISTORY"] or "No crafting/acquisition history yet.") .. "|r")
            row.itemBtn.itemID = nil
            row.priceText:SetText("")
            row.sourceText:SetText("")
            row.charText:SetText("")
            row:Show()
            craftScrollChild:SetHeight(30)
            return
        end

        local sortedHistory = {}
        for i, entry in ipairs(history) do
            sortedHistory[i] = entry
        end

        table.sort(sortedHistory, function(a, b)
            local valA, valB
            if craftSortColumn == "timestamp" then
                valA = a.timestamp or 0
                valB = b.timestamp or 0
            elseif craftSortColumn == "itemName" then
                valA = (a.name or a.itemName or ""):lower()
                valB = (b.name or b.itemName or ""):lower()
            elseif craftSortColumn == "itemPrice" then
                valA = a.itemPrice or 0
                valB = b.itemPrice or 0
            elseif craftSortColumn == "source" then
                valA = (a.source or "Crafted"):lower()
                valB = (b.source or "Crafted"):lower()
            elseif craftSortColumn == "character" then
                valA = (a.character or ""):lower()
                valB = (b.character or ""):lower()
            end

            if craftSortAscending then
                return valA < valB
            else
                return valA > valB
            end
        end)

        for i, entry in ipairs(sortedHistory) do
            local row = GetCraftRow(i)
            row:SetPoint("TOPLEFT", 0, historyYOffset)

            local timeStr = HDG_DataTab.FormatTimestamp(entry.timestamp)
            row.timeText:SetText("|cFF888888" .. timeStr .. "|r")

            local fallbackName = entry.name or entry.itemName or "Unknown"
            local itemName = entry.itemID and HDG_Data.GetLocalizedName(entry.itemID, fallbackName) or fallbackName
            local qty = entry.quantity or entry.count or 1
            local qtyStr = qty > 1 and (" x" .. qty) or ""
            row.itemText:SetText("|cFFFFFFFF" .. itemName .. qtyStr .. "|r")
            row.itemBtn.itemID = entry.itemID
            row.itemBtn.decorID = entry.decorID
            row.itemBtn.itemName = itemName .. qtyStr

            -- Price display (item market value) with tooltip for both prices
            local priceDisplay = "-"
            if entry.itemPrice and entry.itemPrice > 0 then
                priceDisplay = HDG_PriceIntegration and HDG_PriceIntegration.FormatGold(entry.itemPrice) or string.format("%dg", math.floor(entry.itemPrice / 10000))
            end
            row.priceText:SetText("|cFF14b8a6" .. priceDisplay .. "|r")

            -- Store price data for tooltip
            row.materialCost = entry.materialCost
            row.itemPrice = entry.itemPrice
            row.priceSource = entry.priceSource

            -- Source display (Crafted = teal, Learned = gold)
            local sourceVal = entry.source or "Crafted"
            if sourceVal == "Learned" then
                row.sourceText:SetText("|cFFfcd34d" .. sourceVal .. "|r")
            else
                row.sourceText:SetText("|cFF14b8a6" .. sourceVal .. "|r")
            end

            local charName = entry.character or ""
            local realmName = entry.realm or ""
            local charDisplay = charName
            if realmName ~= "" then
                charDisplay = charName .. "-" .. realmName
            end
            row.charText:SetText("|cFF14b8a6" .. charDisplay .. "|r")

            row:Show()
            historyYOffset = historyYOffset - 18
        end

        craftScrollChild:SetHeight(math.abs(historyYOffset) + 10)
    end

    -- Column header click handlers for crafting
    local function OnCraftHeaderClick(header)
        if craftSortColumn == header.column then
            craftSortAscending = not craftSortAscending
        else
            craftSortColumn = header.column
            craftSortAscending = (header.column == "itemName" or header.column == "character")
        end
        UpdateCraftSortArrows()
        RefreshCraftingList()
    end

    craftTimeHeader:SetScript("OnClick", function() OnCraftHeaderClick(craftTimeHeader) end)
    craftItemHeader:SetScript("OnClick", function() OnCraftHeaderClick(craftItemHeader) end)
    craftPriceHeader:SetScript("OnClick", function() OnCraftHeaderClick(craftPriceHeader) end)
    craftSourceHeader:SetScript("OnClick", function() OnCraftHeaderClick(craftSourceHeader) end)
    craftCharHeader:SetScript("OnClick", function() OnCraftHeaderClick(craftCharHeader) end)

    UpdateCraftSortArrows()

    -- Store refresh function
    dataFrame.RefreshCraftingList = RefreshCraftingList
    mainFrame.RefreshHistoryList = RefreshCraftingList  -- Keep compatibility with ConfigTab logging

    yOffset = yOffset - 165

    -- Separator
    local separator = scrollChild:CreateTexture(nil, "ARTWORK")
    separator:SetHeight(1)
    separator:SetPoint("TOPLEFT", 4, yOffset)
    separator:SetPoint("TOPRIGHT", -4, yOffset)
    separator:SetColorTexture(0.3, 0.3, 0.35, 0.5)

    yOffset = yOffset - 15

    -- ========================================================================
    -- FARMING HISTORY SECTION
    -- ========================================================================
    local farmingTitle = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    farmingTitle:SetPoint("TOPLEFT", 4, yOffset)
    farmingTitle:SetText("|cFFfcd34d" .. (L["HEADER_FARMING_HISTORY"] or "Farming History") .. "|r")

    -- Help text explaining how farming tracking works
    local farmingDesc = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    farmingDesc:SetPoint("TOPLEFT", 4, yOffset - 20)
    farmingDesc:SetWidth(CONFIG.MAIN_FRAME_WIDTH - 120)
    farmingDesc:SetJustifyH("LEFT")
    farmingDesc:SetText("|cFF888888Sessions start when lumber enters your bags. Zone shows where the last lumber was collected. Reloading UI ends the session.|r")

    yOffset = yOffset - 18

    -- Export CSV Button for farming
    local farmExportBtn = CreateFrame("Button", nil, scrollChild)
    farmExportBtn:SetSize(100, 22)
    farmExportBtn:SetPoint("TOPRIGHT", -4, yOffset)
    local farmExportTex = farmExportBtn:CreateTexture(nil, "ARTWORK")
    farmExportTex:SetAllPoints()
    farmExportTex:SetTexture(CONFIG.ADDON_TEXTURES.CSV_EXPORT)
    farmExportBtn:SetScript("OnEnter", function() farmExportTex:SetAlpha(0.8) end)
    farmExportBtn:SetScript("OnLeave", function() farmExportTex:SetAlpha(1.0) end)

    farmExportBtn:SetScript("OnClick", function()
        local csv = HDG_DataTab.ExportFarmingToCSV()
        if csv then
            if not HDG_FarmingExportFrame then
                local f = CreateFrame("Frame", "HDG_FarmingExportFrame", UIParent, "BackdropTemplate")
                f:SetSize(500, 350)
                f:SetPoint("CENTER")
                f:SetBackdrop({
                    bgFile = "Interface\\Buttons\\WHITE8X8",
                    edgeFile = "Interface\\Buttons\\WHITE8X8",
                    tile = false, edgeSize = 2,
                    insets = { left = 0, right = 0, top = 0, bottom = 0 }
                })
                f:SetBackdropColor(0.1, 0.1, 0.12, 0.95)
                f:SetBackdropBorderColor(0.08, 0.72, 0.65, 1)
                f:SetFrameStrata("DIALOG")
                f:SetMovable(true)
                f:EnableMouse(true)
                f:RegisterForDrag("LeftButton")
                f:SetScript("OnDragStart", f.StartMoving)
                f:SetScript("OnDragStop", f.StopMovingOrSizing)

                local exportTitle = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
                exportTitle:SetPoint("TOP", 0, -10)
                exportTitle:SetText("|cFF14b8a6Export Farming History|r")

                local instr = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
                instr:SetPoint("TOP", exportTitle, "BOTTOM", 0, -5)
                instr:SetText("|cFF888888Select all (Ctrl+A) then copy (Ctrl+C)|r")

                local sf = CreateFrame("ScrollFrame", nil, f, "UIPanelScrollFrameTemplate")
                sf:SetPoint("TOPLEFT", 15, -50)
                sf:SetPoint("BOTTOMRIGHT", -35, 45)

                local eb = CreateFrame("EditBox", nil, sf)
                eb:SetMultiLine(true)
                eb:SetFontObject("GameFontHighlightSmall")
                eb:SetWidth(440)
                eb:SetAutoFocus(false)
                eb:SetScript("OnEscapePressed", function(self) self:ClearFocus() end)
                sf:SetScrollChild(eb)
                f.editBox = eb

                local closeBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
                closeBtn:SetPoint("BOTTOM", 0, 10)
                closeBtn:SetSize(80, 22)
                closeBtn:SetText("Close")
                closeBtn:SetScript("OnClick", function() f:Hide() end)

                HDG_FarmingExportFrame = f
            end

            HDG_FarmingExportFrame.editBox:SetText(csv)
            HDG_FarmingExportFrame.editBox:HighlightText()
            HDG_FarmingExportFrame.editBox:SetFocus()
            HDG_FarmingExportFrame:Show()
            print("|cFF14b8a6[Housing Decor Guide]|r Exported " .. #HDG_DataTab.GetFarmingHistory() .. " farming entries.")
        end
    end)
    yOffset = yOffset - 25

    -- Farming column headers (reordered: Character at end)
    local farmHeaders = {
        { text = "Date/Time", x = 4, width = 105 },
        { text = "Lumber", x = 112, width = 105 },
        { text = "Collected", x = 220, width = 60 },
        { text = "Rate/hr", x = 283, width = 55 },
        { text = "Duration", x = 340, width = 60 },
        { text = "Zone", x = 405, width = 90 },
        { text = "Character", x = 500, width = 140 }
    }

    for _, header in ipairs(farmHeaders) do
        local headerText = scrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        headerText:SetPoint("TOPLEFT", header.x, yOffset)
        headerText:SetWidth(header.width)
        headerText:SetJustifyH("LEFT")
        headerText:SetText("|cFFfcd34d" .. header.text .. "|r")
    end

    yOffset = yOffset - 20

    -- Farming history container
    local farmContainer = CreateFrame("Frame", nil, scrollChild, "BackdropTemplate")
    farmContainer:SetPoint("TOPLEFT", 4, yOffset)
    farmContainer:SetSize(CONFIG.MAIN_FRAME_WIDTH - 80, 250)
    farmContainer:SetBackdrop({
        bgFile = CONFIG.TEXTURES.WHITE_BG,
        edgeFile = CONFIG.TEXTURES.WHITE_BG,
        tile = false,
        edgeSize = 1,
        insets = { left = 0, right = 0, top = 0, bottom = 0 }
    })
    farmContainer:SetBackdropColor(0.08, 0.08, 0.10, 0.9)
    farmContainer:SetBackdropBorderColor(unpack(HDG_UIHelpers.BORDER_COLOR))

    -- Farming scroll frame
    local farmScrollFrame = CreateFrame("ScrollFrame", nil, farmContainer, "UIPanelScrollFrameTemplate")
    farmScrollFrame:SetPoint("TOPLEFT", 5, -5)
    farmScrollFrame:SetPoint("BOTTOMRIGHT", -25, 5)

    local farmScrollChild = CreateFrame("Frame", nil, farmScrollFrame)
    farmScrollFrame:SetScrollChild(farmScrollChild)
    farmScrollChild:SetWidth(CONFIG.MAIN_FRAME_WIDTH - 120)
    farmScrollChild:SetHeight(1)
    dataFrame.farmScrollChild = farmScrollChild

    if HDG_UIHelpers and HDG_UIHelpers.StyleScrollBar then
        HDG_UIHelpers.StyleScrollBar(farmScrollFrame)
    end

    -- Update scroll child height
    scrollChild:SetHeight(math.abs(yOffset) + 280)

    return dataFrame
end

function HDG_DataTab.RefreshFarmingDisplay()
    if not dataFrame or not dataFrame.farmScrollChild then return end

    local farmScrollChild = dataFrame.farmScrollChild

    -- Clear existing rows
    for _, child in pairs({farmScrollChild:GetChildren()}) do
        child:Hide()
        child:SetParent(nil)
    end

    local history = HDG_DataTab.GetFarmingHistory()
    local yOffset = 0
    local rowHeight = 20

    if #history == 0 then
        local emptyText = farmScrollChild:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        emptyText:SetPoint("TOPLEFT", 4, -20)
        emptyText:SetText("|cFF888888" .. (L["STATUS_NO_FARMING_HISTORY"] or "No farming sessions recorded yet.") .. "\nStart farming lumber to see your history here!|r")
        farmScrollChild:SetHeight(60)
        return
    end

    for i, entry in ipairs(history) do
        local row = CreateFrame("Frame", nil, farmScrollChild, "BackdropTemplate")
        row:SetSize(farmScrollChild:GetWidth() - 10, rowHeight)
        row:SetPoint("TOPLEFT", 0, yOffset)
        row:SetBackdrop({
            bgFile = CONFIG.TEXTURES.WHITE_BG,
            tile = false,
            insets = { left = 0, right = 0, top = 0, bottom = 0 }
        })

        -- Alternate row colors
        if i % 2 == 0 then
            row:SetBackdropColor(0.15, 0.15, 0.18, 0.3)
        else
            row:SetBackdropColor(0, 0, 0, 0)
        end

        -- Timestamp
        local timestamp = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        timestamp:SetPoint("LEFT", 0, 0)
        timestamp:SetWidth(105)
        timestamp:SetJustifyH("LEFT")
        timestamp:SetText(HDG_DataTab.FormatTimestamp(entry.timestamp))

        -- Lumber name (colored by expansion if we can find it)
        -- Prioritize localized name from GetLumberMaterialName over stored English name
        local lumberText = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        lumberText:SetPoint("LEFT", 108, 0)
        lumberText:SetWidth(105)
        lumberText:SetJustifyH("LEFT")
        local lumberInfo = LUMBER_TYPES and LUMBER_TYPES[entry.lumberId]
        local localizedLumberName = HDG_ExpansionData.GetLumberMaterialName(entry.lumberId)
        if lumberInfo then
            local expColor = HDG_ExpansionData.GetColor(lumberInfo.expansion)
            lumberText:SetText(string.format("|cFF%02x%02x%02x%s|r",
                math.min(255, expColor[1] * 255),
                math.min(255, expColor[2] * 255),
                math.min(255, expColor[3] * 255),
                localizedLumberName or lumberInfo.shortName or lumberInfo.name or entry.lumberName))
        else
            lumberText:SetText(localizedLumberName or entry.lumberName or "Unknown")
        end

        -- Collected amount
        local collected = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        collected:SetPoint("LEFT", 216, 0)
        collected:SetWidth(60)
        collected:SetJustifyH("LEFT")
        collected:SetText(string.format("|cFF88FF88%d|r", entry.collected or 0))

        -- Rate per hour
        local rate = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        rate:SetPoint("LEFT", 279, 0)
        rate:SetWidth(55)
        rate:SetJustifyH("LEFT")
        rate:SetText(string.format("|cFFfcd34d%.1f|r", entry.perHour or 0))

        -- Duration
        local duration = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        duration:SetPoint("LEFT", 336, 0)
        duration:SetWidth(60)
        duration:SetJustifyH("LEFT")
        duration:SetText(FormatDuration(entry.duration))

        -- Zone
        local zone = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        zone:SetPoint("LEFT", 401, 0)
        zone:SetWidth(90)
        zone:SetJustifyH("LEFT")
        zone:SetText("|cFF87CEEB" .. (entry.zone or "Unknown") .. "|r")

        -- Character name (last column)
        local charText = row:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        charText:SetPoint("LEFT", 496, 0)
        charText:SetWidth(140)
        charText:SetJustifyH("LEFT")
        local charDisplay = entry.character or ""
        if entry.realm and entry.realm ~= "" then
            charDisplay = charDisplay .. "-" .. entry.realm
        end
        -- Truncate if too long
        if #charDisplay > 20 then
            charDisplay = charDisplay:sub(1, 19) .. "..."
        end
        charText:SetText("|cFF14b8a6" .. charDisplay .. "|r")

        yOffset = yOffset - rowHeight
    end

    farmScrollChild:SetHeight(math.abs(yOffset) + 10)
end

function HDG_DataTab.Show()
    if not dataFrame then
        HDG_DataTab.CreatePanel()
    end
    if dataFrame then
        if dataFrame.RefreshCraftingList then
            dataFrame.RefreshCraftingList()
        end
        HDG_DataTab.RefreshFarmingDisplay()
        dataFrame:Show()
    end
end

function HDG_DataTab.Hide()
    if dataFrame then
        dataFrame:Hide()
    end
end

-- ============================================================================
-- EXPORT TO GLOBAL
-- ============================================================================

_G.HDG_DataTab = HDG_DataTab

return HDG_DataTab
