--[[
============================================================================
UI/TransmogUI/Capture.lua  (added in v14.10.0 — Audit Batch 3 Part 2)
============================================================================

Outfit-capture and import/export dialog logic for the TransmogUI orchestrator.
Owner-pattern: each method takes `owner` (the TUI orchestrator) as first
argument. The orchestrator keeps thin delegator methods so existing call
sites keep working.

Methods owned here (3):
  CaptureCurrentTransmog  — read player's currently-equipped transmog and
                            stage it for save (popup confirms the name)
  ShowExportDialog        — open the export dialog with a Base64-encoded
                            string for the selected outfit
  ShowImportDialog        — open the import dialog accepting a Base64
                            outfit string from another player

Closure / shadowing notes (extending v12.63 + v14.9 lessons):
  - Frame script callbacks here (`function() f:Hide() end`,
    `function() owner:ImportOutfitFromString(text) end`) all close over
    outer-scope variables (`f`, `owner`) — none take `self` parameter,
    so no closure-shadowing risk.
  - The static popup `ETBTUI_CAPTURE_OUTFIT` is defined in TransmogUI.lua
    at file scope (per Blizzard taint rules) and reads `TUI._pendingCapture`.
    After this extraction, `CaptureCurrentTransmog` writes
    `owner._pendingCapture` instead — but at runtime, `owner === TUI`
    (delegator passes `self`), so the popup reads the correct table.

External dependencies pulled from owner:
  owner.ExportSystem      — Base64 encoder/decoder (defined in TransmogUI.lua,
                            already exposed as TUI.ExportSystem)
  owner:ImportOutfitFromString — string -> outfit deserializer
                                 (delegator on TUI -> Outfits:ImportFromString)
  owner:RefreshOutfits    — re-render outfit list after capture
                            (delegator on TUI -> Outfits:Refresh)
============================================================================
]]--
local ADDON_NAME, NS = ...
local ETB = NS.ETB
NS.ETB.TransmogUI = NS.ETB.TransmogUI or {}
NS.ETB.TransmogUI.Capture = NS.ETB.TransmogUI.Capture or {}
local Capture = NS.ETB.TransmogUI.Capture

-- =============================================================================
-- METHODS (extracted from UI/TransmogUI.lua in v14.10.0)
-- =============================================================================

function Capture:CaptureCurrentTransmog(owner)
    local items = {}
    local pieceCount = 0
    local slotNames = {
        [1] = "Head", [3] = "Shoulder", [5] = "Chest", [6] = "Waist",
        [7] = "Legs", [8] = "Feet", [9] = "Wrist", [10] = "Hands",
        [15] = "Back", [16] = "MainHand", [17] = "OffHand",
    }
    
    for invSlot, slotName in pairs(slotNames) do
        local sourceID = nil
        local itemID = nil
        local itemName = nil
        local itemIcon = nil
        
        -- Try to get the TRANSMOG appearance (what it looks like), not the equipped item
        if TransmogUtil and TransmogUtil.CreateTransmogLocation and C_Transmog and C_Transmog.GetSlotVisualInfo then
            local ok, transmogLocation = pcall(TransmogUtil.CreateTransmogLocation, invSlot, 0, 0)
            if ok and transmogLocation then
                -- GetSlotVisualInfo returns: baseSourceID, baseVisualID, appliedSourceID, appliedVisualID, ...
                local vizOk, baseSourceID, baseVisualID, appliedSourceID, appliedVisualID = pcall(C_Transmog.GetSlotVisualInfo, transmogLocation)
                if vizOk then
                    -- Use applied if transmogged, otherwise use base
                    if appliedSourceID and appliedSourceID > 0 then
                        sourceID = appliedSourceID
                    elseif baseSourceID and baseSourceID > 0 then
                        sourceID = baseSourceID
                    end
                    
                    -- Get item info from sourceID
                    if sourceID and sourceID > 0 then
                        local sourceInfo = C_TransmogCollection.GetSourceInfo(sourceID)
                        if sourceInfo and sourceInfo.itemID then
                            itemID = sourceInfo.itemID
                            itemName, _, _, _, _, _, _, _, _, itemIcon = GetItemInfo(itemID)
                        end
                    end
                end
            end
        end
        
        -- Fallback: if we couldn't get transmog, get equipped item appearance
        if not sourceID or sourceID == 0 then
            local itemLink = GetInventoryItemLink("player", invSlot)
            if itemLink then
                itemID = GetItemInfoInstant(itemLink)
                if itemID then
                    itemName, _, _, _, _, _, _, _, _, itemIcon = GetItemInfo(itemID)
                    -- Get the sourceID for this item
                    if C_TransmogCollection and C_TransmogCollection.GetItemInfo then
                        local ok, _, srcID = pcall(C_TransmogCollection.GetItemInfo, itemID)
                        if ok then sourceID = srcID end
                    end
                end
            end
        end
        
        if itemID and itemID > 0 then
            items[slotName] = {
                itemID = itemID,
                sourceID = sourceID,
                name = itemName or ("Item " .. itemID),
                icon = itemIcon,
            }
            pieceCount = pieceCount + 1
        end
    end
    
    if pieceCount == 0 then
        print("|cffff6600[ETB]|r No transmog appearances found to capture!")
        return
    end
    
    -- Store data for the popup's OnAccept handler
    owner._pendingCapture = { items = items, pieceCount = pieceCount }
    StaticPopup_Show("ETBTUI_CAPTURE_OUTFIT")
end


function Capture:ShowExportDialog(owner, outfitID)
    local outfit = ETBTUI_SavedOutfits[outfitID]
    if not outfit then return end
    
    local exportString = owner.ExportSystem:ExportOutfit(outfit)
    if not exportString then
        print("|cffff6600[ETB]|r Failed to export outfit")
        return
    end
    
    -- Create export frame if needed
    if not owner.exportFrame then
        local f = CreateFrame("Frame", "ETBTUIExportFrame", UIParent, "BackdropTemplate")
        f:SetSize(450, 200)
        f:SetPoint("CENTER")
        f:SetBackdrop({
            bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
            edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
            tile = true, tileSize = 32, edgeSize = 32,
            insets = { left = 8, right = 8, top = 8, bottom = 8 }
        })
        f:SetFrameStrata("DIALOG")
        f:EnableMouse(true)
        f:SetMovable(true)
        f:RegisterForDrag("LeftButton")
        f:SetScript("OnDragStart", f.StartMoving)
        f:SetScript("OnDragStop", f.StopMovingOrSizing)
        
        f.title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        f.title:SetPoint("TOP", 0, -15)
        f.title:SetText("|cff00ff00Export Outfit|r")
        
        f.scrollFrame = CreateFrame("ScrollFrame", nil, f, "UIPanelScrollFrameTemplate")
        f.scrollFrame:SetPoint("TOPLEFT", 15, -45)
        f.scrollFrame:SetPoint("BOTTOMRIGHT", -35, 50)
        
        f.editBox = CreateFrame("EditBox", nil, f.scrollFrame)
        f.editBox:SetMultiLine(true)
        f.editBox:SetFontObject("ChatFontNormal")
        f.editBox:SetWidth(380)
        f.editBox:SetAutoFocus(false)
        f.scrollFrame:SetScrollChild(f.editBox)
        
        f.closeBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
        f.closeBtn:SetSize(100, 24)
        f.closeBtn:SetPoint("BOTTOM", 0, 15)
        f.closeBtn:SetText("Close")
        f.closeBtn:SetScript("OnClick", function() f:Hide() end)
        
        f.copyHint = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        f.copyHint:SetPoint("BOTTOMLEFT", 15, 18)
        f.copyHint:SetText("|cff888888Ctrl+A to select all, Ctrl+C to copy|r")
        
        owner.exportFrame = f
    end
    
    owner.exportFrame.title:SetText(string.format("|cff00ff00Export:|r %s", outfit.name))
    owner.exportFrame.editBox:SetText(exportString)
    owner.exportFrame.editBox:HighlightText()
    owner.exportFrame.editBox:SetFocus()
    owner.exportFrame:Show()
end


function Capture:ShowImportDialog(owner)
    -- Create import frame if needed
    if not owner.importFrame then
        local f = CreateFrame("Frame", "ETBTUIImportFrame", UIParent, "BackdropTemplate")
        f:SetSize(450, 200)
        f:SetPoint("CENTER")
        f:SetBackdrop({
            bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
            edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
            tile = true, tileSize = 32, edgeSize = 32,
            insets = { left = 8, right = 8, top = 8, bottom = 8 }
        })
        f:SetFrameStrata("DIALOG")
        f:EnableMouse(true)
        f:SetMovable(true)
        f:RegisterForDrag("LeftButton")
        f:SetScript("OnDragStart", f.StartMoving)
        f:SetScript("OnDragStop", f.StopMovingOrSizing)
        
        f.title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
        f.title:SetPoint("TOP", 0, -15)
        f.title:SetText("|cffaa88ffImport Outfit|r")
        
        f.scrollFrame = CreateFrame("ScrollFrame", nil, f, "UIPanelScrollFrameTemplate")
        f.scrollFrame:SetPoint("TOPLEFT", 15, -45)
        f.scrollFrame:SetPoint("BOTTOMRIGHT", -35, 50)
        
        f.editBox = CreateFrame("EditBox", nil, f.scrollFrame)
        f.editBox:SetMultiLine(true)
        f.editBox:SetFontObject("ChatFontNormal")
        f.editBox:SetWidth(380)
        f.editBox:SetAutoFocus(false)
        f.scrollFrame:SetScrollChild(f.editBox)
        
        f.importBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
        f.importBtn:SetSize(100, 24)
        f.importBtn:SetPoint("BOTTOMLEFT", 50, 15)
        f.importBtn:SetText("|cff00ff00Import|r")
        f.importBtn:SetScript("OnClick", function()
            local text = f.editBox:GetText()
            owner:ImportOutfitFromString(text)
            f:Hide()
        end)
        
        f.closeBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
        f.closeBtn:SetSize(100, 24)
        f.closeBtn:SetPoint("BOTTOMRIGHT", -50, 15)
        f.closeBtn:SetText("Cancel")
        f.closeBtn:SetScript("OnClick", function() f:Hide() end)
        
        f.hint = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        f.hint:SetPoint("TOPLEFT", 15, -35)
        f.hint:SetText("|cff888888Paste an outfit string below:|r")
        
        owner.importFrame = f
    end
    
    owner.importFrame.editBox:SetText("")
    owner.importFrame.editBox:SetFocus()
    owner.importFrame:Show()
end

