--[[
============================================================================
ETB v10.0 - SourcesModal.lua
============================================================================
Modal window showing detailed source information for an item.
============================================================================
]]--

local ADDON_NAME, NS = ...
local ETB = NS.ETB

ETB.SourcesModal = {
    frame = nil,
    currentItem = nil,
}

local Modal = ETB.SourcesModal

-- =============================================================================
-- CREATE
-- =============================================================================

function Modal:Create()
    if self.frame then return self.frame end
    
    local f = CreateFrame("Frame", "ETBSourcesModal", UIParent, "BasicFrameTemplateWithInset")
    f:SetSize(350, 300)
    f:SetPoint("CENTER")
    f:SetMovable(true)
    f:EnableMouse(true)
    f:RegisterForDrag("LeftButton")
    f:SetScript("OnDragStart", f.StartMoving)
    f:SetScript("OnDragStop", f.StopMovingOrSizing)
    f:SetFrameStrata("DIALOG")
    
    f.title = f:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    f.title:SetPoint("TOP", 0, -5)
    f.title:SetText("Item Sources")
    
    -- Item info section
    f.itemIcon = f:CreateTexture(nil, "ARTWORK")
    f.itemIcon:SetSize(40, 40)
    f.itemIcon:SetPoint("TOPLEFT", 15, -35)
    
    f.itemName = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    f.itemName:SetPoint("TOPLEFT", f.itemIcon, "TOPRIGHT", 10, -5)
    f.itemName:SetWidth(260)
    f.itemName:SetJustifyH("LEFT")
    
    f.itemStatus = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    f.itemStatus:SetPoint("TOPLEFT", f.itemName, "BOTTOMLEFT", 0, -5)
    
    -- Separator
    f.sep = f:CreateTexture(nil, "ARTWORK")
    f.sep:SetSize(320, 1)
    f.sep:SetPoint("TOP", 0, -85)
    f.sep:SetColorTexture(0.5, 0.5, 0.5, 0.5)
    
    -- Source info section
    f.sourceHeader = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    f.sourceHeader:SetPoint("TOPLEFT", 15, -95)
    f.sourceHeader:SetText("|cffffd100Source Info:|r")
    
    f.sourceText = f:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    f.sourceText:SetPoint("TOPLEFT", f.sourceHeader, "BOTTOMLEFT", 10, -8)
    f.sourceText:SetWidth(300)
    f.sourceText:SetJustifyH("LEFT")
    f.sourceText:SetSpacing(3)
    
    -- Legacy references for backward compat (point to sourceText)
    f.sourceBoss = f.sourceText
    f.sourceZone = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    f.sourceZone:SetPoint("TOPLEFT", f.sourceText, "BOTTOMLEFT", 0, 0)
    f.sourceZone:SetWidth(0)
    f.sourceZone:Hide()
    f.sourceType = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    f.sourceType:SetPoint("TOPLEFT", f.sourceZone, "BOTTOMLEFT", 0, 0)
    f.sourceType:SetWidth(0)
    f.sourceType:Hide()
    
    -- IDs section (anchored below source text, dynamically positioned)
    f.idsHeader = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    f.idsHeader:SetPoint("TOPLEFT", f.sourceText, "BOTTOMLEFT", -10, -15)
    f.idsHeader:SetText("|cffffd100Technical Info:|r")
    
    f.idText = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    f.idText:SetPoint("TOPLEFT", f.idsHeader, "BOTTOMLEFT", 10, -10)
    f.idText:SetWidth(300)
    f.idText:SetJustifyH("LEFT")
    f.idText:SetTextColor(0.6, 0.6, 0.6)
    
    -- Buttons
    f.linkBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    f.linkBtn:SetSize(100, 22)
    f.linkBtn:SetPoint("BOTTOMLEFT", 15, 10)
    f.linkBtn:SetText("Link in Chat")
    f.linkBtn:SetScript("OnClick", function()
        if Modal.currentItem and Modal.currentItem.itemID then
            local _, link = GetItemInfo(Modal.currentItem.itemID)
            if link then ChatEdit_InsertLink(link) end
        end
    end)
    
    f.tryOnBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    f.tryOnBtn:SetSize(100, 22)
    f.tryOnBtn:SetPoint("LEFT", f.linkBtn, "RIGHT", 10, 0)
    f.tryOnBtn:SetText("Try On")
    f.tryOnBtn:SetScript("OnClick", function()
        if Modal.currentItem and Modal.currentItem.itemID then
            DressUpItemLink("item:" .. Modal.currentItem.itemID)
        end
    end)
    
    f.favBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    f.favBtn:SetSize(100, 22)
    f.favBtn:SetPoint("BOTTOMRIGHT", -15, 10)
    f.favBtn:SetText("★ Favorite")
    f.favBtn:SetScript("OnClick", function()
        if Modal.currentItem and ETB.FavoritesManager then
            ETB.FavoritesManager:ToggleFavorite(Modal.currentItem.itemID)
            Modal:UpdateFavButton()
        end
    end)
    
    -- ESC closes modal (taint-safe: avoids modifying UISpecialFrames)
    f:SetScript("OnKeyDown", function(self, key)
        if key == "ESCAPE" then
            pcall(self.SetPropagateKeyboardInput, self, false)
            self:Hide()
        else
            pcall(self.SetPropagateKeyboardInput, self, true)
        end
    end)
    f:Hide()
    
    self.frame = f
    return f
end

-- =============================================================================
-- METHODS
-- =============================================================================

function Modal:Show(item)
    if not item then return end
    
    -- Redirect to the enhanced AppearanceDetailPanel which now shows
    -- both shared appearances AND detailed source info per item
    if ETB.AppearanceDetail then
        ETB.AppearanceDetail:Show(item)
        return
    end
    
    -- Fallback: create and show the old modal if ADP not available
    if not self.frame then self:Create() end
    
    self.currentItem = item
    local f = self.frame
    
    -- Item info
    f.itemIcon:SetTexture(item.icon or "Interface\\Icons\\INV_Misc_QuestionMark")
    
    local color = ETB:GetQualityColor(item.quality)
    f.itemName:SetText(color .. (item.name or "Unknown") .. "|r")
    
    f.itemStatus:SetText(item.isCollected and "|cff00ff00✓ Collected|r" or "|cffff6666✗ Not Collected|r")
    
    -- Source info - use the SAME FormatSourceTooltip as the tooltip for consistency
    local sourceFound = false
    local sourceLines = {}
    
    -- Primary: SourceMapper tooltip lines (same as hover tooltip)
    if ETB.SourceMapper and ETB.SourceMapper.initialized then
        local tooltipLines = ETB.SourceMapper:FormatSourceTooltip(item.itemID)
        if tooltipLines and #tooltipLines > 0 then
            sourceLines = tooltipLines
            sourceFound = true
        end
    end
    
    -- Fallback: MapperBridge direct
    if not sourceFound and ETB.SourceData_ATT then
        local source = ETB.SourceData_ATT:GetPrimarySource(item.itemID)
        if source and source.name ~= "Unknown" then
            local typeColors = {
                BOSS = "|cffff8000", VENDOR = "|cffffffff", QUEST = "|cffffff00",
                CRAFTED = "|cffff7c0a", WORLD_DROP = "|cff1eff00", PVP = "|cffff0000",
            }
            local typeColor = typeColors[source.type] or "|cff888888"
            sourceLines[#sourceLines + 1] = typeColor .. (source.type or "Unknown") .. "|r"
            if source.name then
                sourceLines[#sourceLines + 1] = "|cffffd100From:|r " .. source.name
            end
            if source.location and source.location ~= "" then
                sourceLines[#sourceLines + 1] = "|cffffd100Location:|r " .. source.location
            end
            sourceFound = true
        end
    end
    
    if sourceFound then
        f.sourceText:SetText(table.concat(sourceLines, "\n"))
    else
        f.sourceText:SetText("|cff888888Unknown source|r")
    end
    
    -- IDs
    local idLines = {}
    idLines[#idLines + 1] = "ItemID: " .. (item.itemID or "?")
    if item.visualID then idLines[#idLines + 1] = "VisualID: " .. item.visualID end
    if item.sourceID then idLines[#idLines + 1] = "SourceID: " .. item.sourceID end
    f.idText:SetText(table.concat(idLines, "\n"))
    
    self:UpdateFavButton()
    
    
    f:Show()
end

function Modal:UpdateFavButton()
    if not self.frame or not self.currentItem then return end
    
    local isFav = ETB.FavoritesManager and ETB.FavoritesManager:IsFavorite(self.currentItem.itemID)
    self.frame.favBtn:SetText(isFav and "★ Unfavorite" or "☆ Favorite")
end

function Modal:Hide()
    if self.frame then self.frame:Hide() end
end

ETB:Debug("SourcesModal", "SourcesModal.lua loaded")
