--[[
============================================================================
ETB - LauncherPanel.lua
============================================================================
Launcher panel with dual model previews:
  Left:  "Open Enhanced Transmog Browser" (collection browsing)
  Right: "Open TransmogUI" (outfit building at NPC)

Shown on minimap button click. Uses Blizzard-style gold borders.
============================================================================
]]--

local ADDON_NAME, NS = ...
local ETB = NS.ETB
if not ETB then return end

ETB.LauncherPanel = ETB.LauncherPanel or {}
local LP = ETB.LauncherPanel

LP.frame = nil

-- ============================================================================
-- CONSTANTS
-- ============================================================================

local PANEL_WIDTH = 520
local PANEL_HEIGHT = 360
local CARD_WIDTH = 230
local CARD_HEIGHT = 310
local CARD_GAP = 16

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

function LP:Create()
    if self.frame then return self.frame end

    local f = CreateFrame("Frame", "ETBLauncherPanel", UIParent, "BackdropTemplate")
    f:SetSize(PANEL_WIDTH, PANEL_HEIGHT)
    f:SetPoint("CENTER", 0, 50)
    f:SetFrameStrata("DIALOG")
    f:SetFrameLevel(200)
    f:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Gold-Border",
        tile = true, tileSize = 32, edgeSize = 32,
        insets = { left = 8, right = 8, top = 8, bottom = 8 },
    })
    f:SetMovable(true)
    f:EnableMouse(true)
    f:RegisterForDrag("LeftButton")
    f:SetScript("OnDragStart", f.StartMoving)
    f:SetScript("OnDragStop", f.StopMovingOrSizing)

    -- Title
    local title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    title:SetPoint("TOP", 0, -14)
    title:SetText("|cffffd100Enhanced Transmog Browser|r")

    -- Close button
    local closeBtn = CreateFrame("Button", nil, f, "UIPanelCloseButton")
    closeBtn:SetPoint("TOPRIGHT", -2, -2)

    -- Close on ESC (SetPropagateKeyboardInput is protected in combat)
    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)

    -- ========================================================================
    -- LEFT CARD: Browser (Lich King model)
    -- ========================================================================
    local leftCard = self:CreateCard(f, -CARD_GAP/2 - CARD_WIDTH/2, "BROWSER")
    -- Try SetCreature first, then SetDisplayInfo as fallback (both pcall-wrapped)
    local creatureOK = pcall(function()
        leftCard.model:SetCreature(36597)  -- The Lich King NPC ID
    end)
    if not creatureOK then
        pcall(function()
            leftCard.model:SetDisplayInfo(28641)  -- Lich King display ID fallback
        end)
    end
    leftCard.model:SetRotation(-0.3)
    f.leftCard = leftCard

    -- ========================================================================
    -- RIGHT CARD: TransmogUI (Player character model)
    -- ========================================================================
    local rightCard = self:CreateCard(f, CARD_GAP/2 + CARD_WIDTH/2, "TRANSMOGUI")
    rightCard.model:SetUnit("player")
    rightCard.model:SetRotation(0.3)
    f.rightCard = rightCard

    -- ========================================================================
    -- COLLECTION STATS BAR
    -- ========================================================================
    f.statsText = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    f.statsText:SetPoint("BOTTOM", 0, 12)
    f.statsText:SetTextColor(0.6, 0.6, 0.6)

    f:Hide()
    self.frame = f
    return f
end

-- ============================================================================
-- CREATE CARD
-- ============================================================================

function LP:CreateCard(parent, xOffset, cardType)
    local card = CreateFrame("Frame", nil, parent, "BackdropTemplate")
    card:SetSize(CARD_WIDTH, CARD_HEIGHT)
    card:SetPoint("TOP", parent, "TOP", xOffset, -38)
    card:SetBackdrop({
        bgFile = "Interface\\Collections\\CollectionsBackgroundTile",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        tile = true, tileSize = 256, edgeSize = 12,
        insets = { left = 2, right = 2, top = 2, bottom = 2 },
    })

    -- Model
    card.model = CreateFrame("DressUpModel", nil, card)
    card.model:SetSize(CARD_WIDTH - 8, CARD_HEIGHT - 60)
    card.model:SetPoint("TOP", 0, -4)
    card.model:SetPosition(0, 0, 0)
    card.model:EnableMouse(false)  -- Let clicks pass through to card
    card.model:Show()

    -- Button at bottom
    card.button = CreateFrame("Button", nil, card, "UIPanelButtonTemplate")
    card.button:SetSize(CARD_WIDTH - 16, 28)
    card.button:SetPoint("BOTTOM", 0, 8)

    -- Click handler function (shared by button AND card)
    local clickAction
    if cardType == "BROWSER" then
        card.button:SetText("Open Enhanced Transmog Browser")
        clickAction = function()
            LP:Hide()
            if ETB.MainFrame then
                ETB.MainFrame:Toggle()
            end
        end
    elseif cardType == "TRANSMOGUI" then
        card.button:SetText("Open TransmogUI")
        clickAction = function()
            LP:Hide()
            if ETB.TransmogUI then
                local TUI = ETB.TransmogUI
                if TUI.Show then
                    TUI:Show()
                elseif TUI.frame then
                    TUI.frame:Show()
                end
            end
        end
    end

    -- Button click
    card.button:SetScript("OnClick", clickAction)

    -- Make entire card clickable (model area too)
    card:EnableMouse(true)
    card:SetScript("OnMouseUp", function(self, button)
        if button == "LeftButton" and clickAction then
            clickAction()
        end
    end)

    -- Description text above button
    card.desc = card:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    card.desc:SetPoint("BOTTOM", card.button, "TOP", 0, 4)
    card.desc:SetWidth(CARD_WIDTH - 20)
    card.desc:SetJustifyH("CENTER")

    if cardType == "BROWSER" then
        card.desc:SetText("|cff888888Browse & discover appearances\nTrack collection progress|r")
    elseif cardType == "TRANSMOGUI" then
        card.desc:SetText("|cff888888Build outfits & apply transmogs\nWorks anywhere for planning|r")
    end

    return card
end

-- ============================================================================
-- SHOW / HIDE / TOGGLE
-- ============================================================================

function LP:Show()
    if not self.frame then self:Create() end

    -- Update stats (lightweight text update only)
    if ETB.BlizzardData then
        local stats = ETB.BlizzardData:GetAllStats()
        if stats and stats.total > 0 then
            self.frame.statsText:SetText(string.format(
                "Collection: |cff00ff00%s|r / %s appearances (|cffffff00%.1f%%|r)",
                ETB:FormatNumber(stats.collected),
                ETB:FormatNumber(stats.total),
                stats.percent))
        end
    end

    -- Models are loaded once in Create() — DO NOT reload here.
    -- SetCreature / SetUnit on every Show() causes graphics pipeline flush
    -- which triggers the game freeze + retexture.

    self.frame:Show()
end

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

function LP:Toggle()
    if self.frame and self.frame:IsShown() then
        self:Hide()
    else
        self:Show()
    end
end

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