local _, ns = ...

------------------------------------------------------------
-- Welcome window: shown once on first login
------------------------------------------------------------
local WELCOME_W = 460
local PAD = 20

local w = CreateFrame("Frame", "YippYappWelcome", UIParent, "BackdropTemplate")
w:SetSize(WELCOME_W, 440)
w:SetPoint("CENTER")
w:SetMovable(true)
w:EnableMouse(true)
w:RegisterForDrag("LeftButton")
w:SetScript("OnDragStart", w.StartMoving)
w:SetScript("OnDragStop", w.StopMovingOrSizing)
w:SetClampedToScreen(true)
w:SetFrameStrata("DIALOG")
w:SetBackdrop({
    bgFile   = "Interface\\Buttons\\WHITE8x8",
    edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
    edgeSize = 16,
    insets   = { left = 4, right = 4, top = 4, bottom = 4 },
})
w:SetBackdropColor(0.05, 0.05, 0.05, 0.97)
w:SetBackdropBorderColor(0.0, 1.0, 0.3, 0.8)
ns.SmoothFrame(w)
w:Hide()

-- ESC to close (OnShow is set later with full logic)
w:SetScript("OnHide", function()
    for i = #UISpecialFrames, 1, -1 do
        if UISpecialFrames[i] == "YippYappWelcome" then
            table.remove(UISpecialFrames, i)
            break
        end
    end
end)

------------------------------------------------------------
-- Header
------------------------------------------------------------
local icon = w:CreateTexture(nil, "ARTWORK")
icon:SetSize(36, 36)
icon:SetPoint("TOPLEFT", PAD, -16)
icon:SetTexture("Interface\\AddOns\\YippYappHelper\\Media\\YippYappHelper")
icon:SetTexCoord(0.08, 0.92, 0.08, 0.92)

local title = w:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
title:SetPoint("LEFT", icon, "RIGHT", 10, 5)
ns.ApplyTextShadow(title)

local sub = w:CreateFontString(nil, "OVERLAY", "GameFontNormal")
sub:SetPoint("LEFT", icon, "RIGHT", 10, -10)
sub:SetTextColor(0.45, 0.45, 0.45)
sub:SetText("Your Midnight Season 1 Companion")

local y = -66

-- Divider
local div1 = w:CreateTexture(nil, "ARTWORK")
div1:SetHeight(1)
div1:SetPoint("TOPLEFT", PAD, y)
div1:SetPoint("TOPRIGHT", -PAD, y)
div1:SetColorTexture(0.4, 0.4, 0.4, 0.3)
y = y - 14

------------------------------------------------------------
-- What's New
------------------------------------------------------------
local sections = {
    {
        title = "What's New in v2.5.0",
        items = {
            "|cffff6666Interrupt Tracker|r |cffff8800(BETA)|r - party-wide interrupt CDs, taint-safe for Midnight M+.",
            "|cff00d4ffM+ Completion Popup|r |cffff8800(BETA)|r - new rating + party keys with click-to-teleport.",
            "|cffffc840Utility Advisor|r |cffff8800(BETA)|r - per-class utility tips on mythic entry.",
            "|cff00aaffRaid Addon Scanner|r - shows who in raid has YippYapp installed.",
            "|cffffc840Settings moved in-addon|r - gear button, /yhopts, or /yyhinterrupts.",
            "|cff00d4ffM+ page|r - strictly 5-man scoped, new tab style, /yyhmplustest preview.",
            "|cff00aaffReady Check|r - big perf pass for 30-man raids, early-finish fade.",
            "|cffb76affL'ura Runes removed|r - Midnight encounter taint killed every signaling primitive.",
            "|cff888888UI polish|r - unified darker theme, drag-to-move interrupt frame, taint fixes.",
        },
    },
}

for _, section in ipairs(sections) do
    local sTitle = w:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    sTitle:SetPoint("TOPLEFT", PAD, y)
    sTitle:SetTextColor(unpack(ns.COLORS.TEXT_HEADER))
    sTitle:SetText(section.title)
    ns.ApplyTextShadow(sTitle)
    y = y - 20

    -- Strip color escapes when measuring the line length so the wrap
    -- estimate isn't inflated by hidden |cffXXXXXX...|r tags.
    local function visibleLen(s)
        return #(s:gsub("|c%x%x%x%x%x%x%x%x", ""):gsub("|r", ""))
    end

    for _, line in ipairs(section.items) do
        local fs = w:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        fs:SetPoint("TOPLEFT", PAD + 8, y)
        fs:SetWidth(WELCOME_W - PAD * 2 - 16)
        fs:SetJustifyH("LEFT")
        fs:SetWordWrap(true)
        fs:SetTextColor(0.6, 0.6, 0.6)
        fs:SetText("|cff555555>|r  " .. line)
        -- GetStringHeight is unreliable until the frame has been laid
        -- out at least once. Always estimate from character count so
        -- the layout is deterministic on first show. Conservative
        -- CHARS_PER_LINE + a slightly larger per-line height ensures
        -- no overlap even when lines wrap tighter than estimated.
        local CHARS_PER_LINE = 55
        local lines = math.max(1, math.ceil(visibleLen(line) / CHARS_PER_LINE))
        local h = lines * 14 + 4
        y = y - (h + 6)
    end

    y = y - 8
end

y = y - 4

-- Divider
local div2 = w:CreateTexture(nil, "ARTWORK")
div2:SetHeight(1)
div2:SetPoint("TOPLEFT", PAD, y)
div2:SetPoint("TOPRIGHT", -PAD, y)
div2:SetColorTexture(0.4, 0.4, 0.4, 0.3)
y = y - 14

------------------------------------------------------------
-- Quick Access section
------------------------------------------------------------
local macroTitle = w:CreateFontString(nil, "OVERLAY", "GameFontNormal")
macroTitle:SetPoint("TOPLEFT", PAD, y)
macroTitle:SetText("|cffaaaaaaQuick Access|r")
y = y - 24

-- Macro icon on the right
local dragBtn = CreateFrame("Button", "YippYappMacroDrag", w)
dragBtn:SetSize(44, 44)
dragBtn:SetPoint("TOPRIGHT", -PAD - 10, y + 2)
dragBtn:RegisterForDrag("LeftButton")

local dragIcon = dragBtn:CreateTexture(nil, "ARTWORK")
dragIcon:SetSize(44, 44)
dragIcon:SetPoint("CENTER")
dragIcon:SetTexture(1998635)
dragIcon:SetTexCoord(0.08, 0.92, 0.08, 0.92)

local dragBorder = dragBtn:CreateTexture(nil, "OVERLAY")
dragBorder:SetSize(78, 78)
dragBorder:SetPoint("CENTER")
dragBorder:SetTexture("Interface\\Buttons\\UI-Quickslot2")

local dragLabel = w:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
dragLabel:SetPoint("TOP", dragBtn, "BOTTOM", 0, -4)
dragLabel:SetTextColor(0.45, 0.45, 0.45)
dragLabel:SetText("Drag to bar!")

dragBtn:SetScript("OnDragStart", function()
    if InCombatLockdown() then return end
    local idx = GetMacroIndexByName("YippYapp")
    if idx and idx > 0 then
        PickupMacro(idx)
    end
end)

dragBtn:SetScript("OnEnter", function(self)
    GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
    GameTooltip:SetText("|cff00ff00YippYapp Helper|r")
    GameTooltip:AddLine("Drag to your action bar", 1, 1, 1)
    GameTooltip:AddLine("/yh to open", 0.5, 0.5, 0.5)
    GameTooltip:Show()
end)
dragBtn:SetScript("OnLeave", GameTooltip_Hide)

-- Description text (left of the icon)
local macroDesc = w:CreateFontString(nil, "OVERLAY", "GameFontNormal")
macroDesc:SetPoint("TOPLEFT", PAD + 8, y)
macroDesc:SetWidth(WELCOME_W - PAD * 2 - 80)
macroDesc:SetJustifyH("LEFT")
macroDesc:SetWordWrap(true)
macroDesc:SetTextColor(0.65, 0.65, 0.65)
macroDesc:SetText(
    "Drag the icon to your action bar\nfor one-click access."
)

y = y - 40

local cmdFs = w:CreateFontString(nil, "OVERLAY", "GameFontNormal")
cmdFs:SetPoint("TOPLEFT", PAD + 8, y)
cmdFs:SetWidth(WELCOME_W - PAD * 2 - 16)
cmdFs:SetJustifyH("LEFT")
cmdFs:SetTextColor(0.55, 0.55, 0.55)
cmdFs:SetText("Or type |cff00ff00/yh|r to open  |cff555555\194\183|r  Use the minimap button")

y = y - 28

------------------------------------------------------------
-- Profile selector section
------------------------------------------------------------
local div3 = w:CreateTexture(nil, "ARTWORK")
div3:SetHeight(1)
div3:SetPoint("TOPLEFT", PAD, y)
div3:SetPoint("TOPRIGHT", -PAD, y)
div3:SetColorTexture(0.4, 0.4, 0.4, 0.3)
y = y - 14

local profTitle = w:CreateFontString(nil, "OVERLAY", "GameFontNormal")
profTitle:SetPoint("TOPLEFT", PAD, y)
profTitle:SetTextColor(unpack(ns.COLORS.TEXT_HEADER))
profTitle:SetText("Select Your Profile")
ns.ApplyTextShadow(profTitle)
y = y - 18

local profDesc = w:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
profDesc:SetPoint("TOPLEFT", PAD + 8, y)
profDesc:SetWidth(WELCOME_W - PAD * 2 - 16)
profDesc:SetJustifyH("LEFT")
profDesc:SetTextColor(unpack(ns.COLORS.TEXT_SECONDARY))
profDesc:SetText("This controls which crests the addon considers precious. Pick the one that matches your gameplay.")
y = y - 28

-- Profile buttons (one per profile, 2 columns)
local PROF_BTN_W = math.floor((WELCOME_W - PAD * 2 - 10) / 2)
local PROF_BTN_H = 26
local welcomeProfileBtns = {}

for i, p in ipairs(ns.PROFILES) do
    local col = (i - 1) % 2
    local row = math.floor((i - 1) / 2)
    local bx = PAD + col * (PROF_BTN_W + 10)
    local by = y - row * (PROF_BTN_H + 4)

    local pb = CreateFrame("Button", nil, w, "BackdropTemplate")
    pb:SetSize(PROF_BTN_W, PROF_BTN_H)
    pb:SetPoint("TOPLEFT", bx, by)
    pb:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        edgeSize = 8,
        insets = { left = 2, right = 2, top = 2, bottom = 2 },
    })
    pb:SetBackdropColor(0.1, 0.1, 0.1, 0.8)
    pb:SetBackdropBorderColor(0.3, 0.3, 0.3, 0.5)
    ns.AddGlowHighlight(pb, 0.06)

    local pbFs = pb:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    pbFs:SetPoint("CENTER")

    local pid = p.id
    pb:SetScript("OnClick", function()
        YippYappHelperDB.profile = pid
        -- Update button highlights
        for _, wb in ipairs(welcomeProfileBtns) do
            local isActive = (YippYappHelperDB.profile == wb.pid)
            if isActive then
                wb.btn:SetBackdropColor(0.0, 0.3, 0.1, 1)
                wb.btn:SetBackdropBorderColor(0.0, 1.0, 0.3, 0.8)
            else
                wb.btn:SetBackdropColor(0.1, 0.1, 0.1, 0.8)
                wb.btn:SetBackdropBorderColor(0.3, 0.3, 0.3, 0.5)
            end
        end
    end)

    table.insert(welcomeProfileBtns, { btn = pb, fs = pbFs, pid = pid })
end

-- Set labels, title, and profile highlights on show
w:SetScript("OnShow", function()
    tinsert(UISpecialFrames, "YippYappWelcome")

    -- Dynamic title based on first install vs update
    local seenBefore = YippYappHelperDB and YippYappHelperDB.lastSeenVersion
    if seenBefore then
        title:SetText("|cff00ff00What's New|r")
        sub:SetText("YippYapp Helper v" .. (ns.ADDON_VERSION or "2.0.0"))
    else
        title:SetText("|cff00ff00Welcome to YippYapp Helper|r")
        sub:SetText("Your Midnight Season 1 Companion")
    end

    -- Profile button highlights
    local currentId = YippYappHelperDB and YippYappHelperDB.profile or "heroic"
    for _, wb in ipairs(welcomeProfileBtns) do
        local p
        for _, prof in ipairs(ns.PROFILES) do
            if prof.id == wb.pid then p = prof break end
        end
        local color = "|cff00aaff"
        local displayName = p and p.name or wb.pid
        local displayDesc = p and p.desc
        if displayDesc then
            displayName = displayName .. " |cff888888" .. displayDesc .. "|r"
        end
        wb.fs:SetText(color .. displayName .. "|r")
        if wb.pid == currentId then
            wb.btn:SetBackdropColor(0.0, 0.3, 0.1, 1)
            wb.btn:SetBackdropBorderColor(0.0, 1.0, 0.3, 0.8)
        else
            wb.btn:SetBackdropColor(0.1, 0.1, 0.1, 0.8)
            wb.btn:SetBackdropBorderColor(0.3, 0.3, 0.3, 0.5)
        end
    end
end)

local profRows = math.ceil(#ns.PROFILES / 2)
y = y - profRows * (PROF_BTN_H + 4) - 8

------------------------------------------------------------
-- "Got it" button
------------------------------------------------------------
local gotItBtn = CreateFrame("Button", nil, w, "BackdropTemplate")
gotItBtn:SetSize(160, 36)
gotItBtn:SetPoint("BOTTOM", 0, 18)
gotItBtn:SetBackdrop({
    bgFile   = "Interface\\Buttons\\WHITE8x8",
    edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
    edgeSize = 12,
    insets   = { left = 3, right = 3, top = 3, bottom = 3 },
})
gotItBtn:SetBackdropColor(0.0, 0.4, 0.15, 1)
gotItBtn:SetBackdropBorderColor(0.0, 1.0, 0.3, 0.8)

local gotItFs = gotItBtn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
gotItFs:SetPoint("CENTER")
gotItFs:SetText("|cffffffffGot it!|r")

gotItBtn:SetScript("OnEnter", function(self)
    self:SetBackdropColor(0.0, 0.55, 0.2, 1)
end)
gotItBtn:SetScript("OnLeave", function(self)
    self:SetBackdropColor(0.0, 0.4, 0.15, 1)
end)

gotItBtn:SetScript("OnClick", function()
    YippYappHelperDB.lastSeenVersion = ns.ADDON_VERSION or "2.0.0"
    w:Hide()
end)

-- Resize to fit all content + button padding
local totalH = math.abs(y) + 36 + 36
w:SetHeight(math.max(400, totalH))

------------------------------------------------------------
function ns:ShowWelcome()
    w:Show()
end
