--[[
============================================================================
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 = 740
local PANEL_HEIGHT = 420
local CARD_WIDTH = 215
local CARD_HEIGHT = 290
local CARD_GAP = 14

-- ============================================================================
-- 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)

    -- ESC closes panel. v14.10.1: see Construction.lua for rationale.
    if UISpecialFrames then
        local already = false
        for _, name in ipairs(UISpecialFrames) do
            if name == "ETBLauncherPanel" then already = true; break end
        end
        if not already then tinsert(UISpecialFrames, "ETBLauncherPanel") end
    end

    -- ========================================================================
    -- LEFT CARD: Browser (Lich King model)
    -- ========================================================================
    local cardSpacing = CARD_WIDTH + CARD_GAP
    local leftCard = self:CreateCard(f, -cardSpacing, "BROWSER")
    local creatureOK = pcall(function()
        leftCard.model:SetCreature(36597)  -- The Lich King NPC ID
    end)
    if not creatureOK then
        pcall(function()
            leftCard.model:SetDisplayInfo(28641)
        end)
    end
    leftCard.model:SetRotation(-0.3)
    f.leftCard = leftCard

    -- ========================================================================
    -- CENTER CARD: TransmogUI (Player character model)
    -- ========================================================================
    local centerCard = self:CreateCard(f, 0, "TRANSMOGUI")
    centerCard.model:SetUnit("player")
    centerCard.model:SetRotation(0.3)
    f.centerCard = centerCard

    -- ========================================================================
    -- RIGHT CARD: Raid BiS Browser (Ra-den model)
    -- ========================================================================
    local rightCard = self:CreateCard(f, cardSpacing, "RAIDBIS")
    -- SetCreature silently fails for NPCs not in local cache.
    -- Use SetDisplayInfo directly with Ra-den's creature display ID.
    pcall(function() rightCard.model:SetDisplayInfo(47194) end)  -- Ra-den
    rightCard.model:SetRotation(-0.2)
    f.rightCard = rightCard

    -- ========================================================================
    -- COLLECTION STATS PILLS (below title, above cards)
    -- ========================================================================
    f.statsText = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    f.statsText:SetPoint("TOP", title, "BOTTOM", 0, -4)
    f.statsText:SetTextColor(0.6, 0.6, 0.6)

    -- ========================================================================
    -- QUICK ACCESS ROW (below cards)
    -- ========================================================================
    local qaY = -358
    local qaWidth = 140
    local qaHeight = 28
    local qaGap = 10

    local wishlistBtn = CreateFrame("Button", nil, f, "BackdropTemplate")
    wishlistBtn:SetSize(qaWidth, qaHeight)
    wishlistBtn:SetPoint("TOP", f, "TOP", -(qaWidth + qaGap), qaY)
    wishlistBtn:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        tile = false, edgeSize = 8,
        insets = { left = 2, right = 2, top = 2, bottom = 2 },
    })
    wishlistBtn:SetBackdropColor(0.1, 0.1, 0.15, 0.9)
    wishlistBtn:SetBackdropBorderColor(0.4, 0.4, 0.4)
    local wlText = wishlistBtn:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    wlText:SetPoint("CENTER")
    wlText:SetText("|cffffcc00Wishlist|r")
    f.wlQAText = wlText
    wishlistBtn:SetScript("OnClick", function()
        f:Hide()
        if ETB.WishlistPanel then ETB.WishlistPanel:Toggle() end
    end)
    wishlistBtn:SetScript("OnEnter", function(self)
        self:SetBackdropBorderColor(1, 0.82, 0)
        GameTooltip:SetOwner(self, "ANCHOR_BOTTOM")
        local count = ETB.Wishlist and ETB.Wishlist:GetItemCount() or 0
        GameTooltip:AddLine("Open Wishlist (" .. count .. " items)")
        GameTooltip:Show()
    end)
    wishlistBtn:SetScript("OnLeave", function(self) self:SetBackdropBorderColor(0.4, 0.4, 0.4); GameTooltip:Hide() end)

    local tutorialBtn = CreateFrame("Button", nil, f, "BackdropTemplate")
    tutorialBtn:SetSize(qaWidth, qaHeight)
    tutorialBtn:SetPoint("TOP", f, "TOP", qaWidth + qaGap, qaY)
    tutorialBtn:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        tile = false, edgeSize = 8,
        insets = { left = 2, right = 2, top = 2, bottom = 2 },
    })
    tutorialBtn:SetBackdropColor(0.1, 0.1, 0.15, 0.9)
    tutorialBtn:SetBackdropBorderColor(0.4, 0.4, 0.4)
    local tText = tutorialBtn:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    tText:SetPoint("CENTER")
    tText:SetText("|cff00ccffTutorial|r")
    tutorialBtn:SetScript("OnClick", function()
        f:Hide()
        if ETB.Tutorial then ETB.Tutorial:Toggle() end
    end)
    tutorialBtn:SetScript("OnEnter", function(self)
        self:SetBackdropBorderColor(0, 0.8, 1)
        GameTooltip:SetOwner(self, "ANCHOR_BOTTOM")
        GameTooltip:AddLine("Open Getting Started Guide")
        GameTooltip:Show()
    end)
    tutorialBtn:SetScript("OnLeave", function(self) self:SetBackdropBorderColor(0.4, 0.4, 0.4); GameTooltip:Hide() end)

    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, -56)
    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("Transmog Browser")
        clickAction = function()
            LP:Hide()
            if ETB.MainFrame then
                ETB.MainFrame:Toggle()
            end
        end
    elseif cardType == "TRANSMOGUI" then
        card.button:SetText("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
    elseif cardType == "RAIDBIS" then
        card.button:SetText("Raid BiS Browser")
        clickAction = function()
            LP:Hide()
            -- Lazy-load ERB on first click (triggers LoadAddOn)
            local ERB = ETB:GetERB()
            if ERB and ERB.MainFrame then
                ERB.MainFrame:Toggle()
            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")
    elseif cardType == "RAIDBIS" then
        card.desc:SetText("|cff888888BiS gear rankings by slot\nBoss tooltips & spec switching|r")
    end

    return card
end

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

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

    -- Update stats
    if ETB.BlizzardData then
        local stats = ETB.BlizzardData:GetAllStats()
        local erbInfo = ""
        local ERB = ETB.ERB
        if ERB and ERB.DataBridge and ERB.DataBridge.playerSpecName then
            erbInfo = string.format(" | |cff00ccffBiS:|r %s %s (%d items)",
                ERB.DataBridge.playerSpecName,
                ERB.DataBridge:GetSourceLabel(ERB.DataBridge.activeSource) or "",
                ERB.DataBridge.itemCount or 0)
        end
        if stats and stats.total > 0 then
            self.frame.statsText:SetText(string.format(
                "Collection: |cff00ff00%s|r / %s appearances (|cffffff00%.1f%%|r)%s",
                ETB:FormatNumber(stats.collected),
                ETB:FormatNumber(stats.total),
                stats.percent,
                erbInfo))
        end
    end

    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")
