-- ETB Tutorial — Multi-page in-game guide
-- Shows on first login. Can be re-opened with /etb tutorial.
-- Dismissed permanently with "Don't show again" checkbox.
local ADDON_NAME, NS = ...
local ETB = NS.ETB
if not ETB then return end

ETB.Tutorial = {}
local TUT = ETB.Tutorial

TUT.frame = nil
TUT.currentPage = 1

-- ============================================================================
-- TUTORIAL PAGES
-- ============================================================================

local PAGES = {
    {
        title = "Welcome to Enhanced Transmog Browser",
        lines = {
            "|cffffd100ETB|r is your all-in-one companion for transmog",
            "collection tracking and raid BiS gear in MoP Classic.",
            "",
            "|cff00ccffWhat's included:|r",
            "",
            "|cffffd100Transmog Browser|r — Browse 54,575 appearances",
            "across Classic, TBC, Wrath, Cata, and MoP.",
            "",
            "|cffffd100TransmogUI|r — Build outfits and preview",
            "transmogs on your character model.",
            "",
            "|cffffd100Raid BiS Browser|r — 1,401 BiS items ranked",
            "per slot for every class and spec.",
            "",
            "|cffffd100Boss Tooltips|r — Hover any boss to see",
            "transmog drops and BiS rankings.",
        },
    },
    {
        title = "The Launcher Panel",
        lines = {
            "Click the |cffffd100minimap button|r to open the",
            "|cff00ccffLauncher Panel|r with three cards:",
            "",
            "|cffffd100Left:|r Transmog Browser",
            "  Browse and discover appearances.",
            "  Track your collection progress.",
            "",
            "|cffffd100Center:|r TransmogUI",
            "  Build outfits and apply transmogs.",
            "  Works anywhere for planning.",
            "",
            "|cffffd100Right:|r Raid BiS Browser",
            "  BiS gear rankings by slot.",
            "  Boss tooltips and spec switching.",
            "",
            "|cff888888Tip: Right-click the minimap button",
            "to skip the launcher and open the",
            "Transmog Browser directly.|r",
        },
    },
    {
        title = "Minimap Button Shortcuts",
        lines = {
            "The minimap button has several shortcuts:",
            "",
            "|cffffff00Left-click|r",
            "  Open the Launcher Panel",
            "",
            "|cffffff00Right-click|r",
            "  Quick-open Transmog Browser",
            "",
            "|cffffff00Shift + Left-click|r",
            "  Quick-open TransmogUI",
            "",
            "|cffffff00Ctrl + Left-click|r",
            "  Open Raid BiS Browser",
            "",
            "|cffffff00Middle-click|r",
            "  Open Raid BiS Browser",
            "",
            "|cff888888You can drag the button around",
            "the minimap to reposition it.|r",
        },
    },
    {
        title = "Transmog Browser",
        lines = {
            "The |cffffd100Transmog Browser|r lets you explore",
            "every transmog appearance in the game.",
            "",
            "|cff00ccffFeatures:|r",
            "  Filter by |cffffff00expansion|r — Classic through MoP",
            "  Filter by |cffffff00armor type|r — Cloth to Plate + weapons",
            "  Filter by |cffffff00source|r — Dungeon, Raid, Quest, Crafted",
            "",
            "|cff00ff00" .. string.char(226,156,147) .. "|r = Collected  |cffff4444" .. string.char(226,156,151) .. "|r = Not Collected",
            "  Tracks by appearance, not by item.",
            "  If you got the same look from another",
            "  source, it still counts!",
            "",
            "|cffffff00Favorites|r — Alt+click to star items",
            "|cffffff00Wishlist|r — Ctrl+Right-click to track",
            "  |cff00ccff/etb wishlist|r to open panel",
            "  |cff00ccff/etb farm|r for farming guide",
            "|cffffff00Sets|r — Community + custom outfit sets",
            "",
            "Open with: |cff00ccff/etb|r",
        },
    },
    {
        title = "Item Tooltip Panel",
        lines = {
            "When you hover any equippable item,",
            "a |cffffd100gold-bordered panel|r appears next to",
            "the Blizzard tooltip showing ETB info:",
            "",
            "|cff00ff00" .. string.char(226,156,147) .. " Appearance Collected|r",
            "  or |cffff4444" .. string.char(226,156,151) .. " Not Collected|r",
            "",
            "|cffffd100Source:|r Boss name, dungeon, or vendor",
            "|cffffd100Location:|r Instance or zone name",
            "",
            "|cff66bbffCrafted:|r Profession name + recipe",
            "  Full reagent list with quantities",
            "",
            "|cffff8000BiS Rank #1|r — if the item is on your",
            "  active BiS list, shows its ranking",
            "",
            "|cffffd100" .. string.char(226,152,133) .. " Favorited|r — if you've starred it",
            "|cffffcc00On your wishlist|r — if tracked",
        },
    },
    {
        title = "Raid BiS Browser",
        lines = {
            "The |cff00ccffRaid BiS Browser|r shows Best-in-Slot",
            "gear ranked per slot for your spec.",
            "",
            "|cffffff00Two BiS Sources:|r",
            "  |cffffd100WoWTBC|r (default) — 1,151 items",
            "    More alternatives per slot",
            "  |cffffd100WoWHead|r — 505 items",
            "    Curated top picks",
            "",
            "Switch sources with the button in the",
            "top bar or |cff00ccff/erb source|r.",
            "",
            "|cffffff00Two Phases:|r",
            "  |cffffd100Pre-Raid|r — Dungeons, T14, world bosses",
            "  |cffffd100Phase 3|r — Throne of Thunder, Nalak, Oondasta",
            "",
            "Your spec is |cff00ff00auto-detected|r on login.",
            "Switch manually: |cff00ccff/erb spec|r",
            "",
            "Open with: |cff00ccff/erb|r",
        },
    },
    {
        title = "Boss Tooltips",
        lines = {
            "Hover any |cffff4444boss NPC|r in the world to see",
            "two sections added to the tooltip:",
            "",
            "|cff00ccff1. ERB BiS Section|r",
            "  Shows BiS drops from this boss for your",
            "  spec, grouped by slot with alternatives.",
            "  Phase-aware: ToT bosses show Phase 3 only.",
            "",
            "|cffffff002. ETB Loot Section|r",
            "  All transmog drops with collection status.",
            "  Auto-filters by raid difficulty when",
            "  you're inside an instance.",
            "",
            "|cff888888Inside 25-Man Heroic?|r",
            "  Only 25H drops shown. Clean and focused.",
            "",
            "|cff888888Outside instances?|r",
            "  All difficulties shown for reference.",
            "",
            "Tooltips |cff00ff00persist|r — no re-hovering needed.",
        },
    },
    {
        title = "Commands & Tips",
        lines = {
            "|cffffff00ETB Commands:|r",
            "  |cff00ccff/etb|r — Toggle Transmog Browser",
            "  |cff00ccff/etb tui|r — Open TransmogUI",
            "  |cff00ccff/etb diag|r — Diagnostic info",
            "  |cff00ccff/etb stats|r — Collection statistics",
            "",
            "|cffffff00ERB Commands:|r",
            "  |cff00ccff/erb|r — Toggle Raid BiS Browser",
            "  |cff00ccff/erb source|r — Switch BiS list",
            "  |cff00ccff/erb spec|r — List or switch specs",
            "  |cff00ccff/erb status|r — Character + BiS stats",
            "  |cff00ccff/erb diag|r — Full diagnostics",
            "",
            "|cffffff00Re-open this tutorial:|r",
            "  |cff00ccff/etb tutorial|r",
            "",
            "|cff888888Memory:|r ETB defers 1.1 MB of data tables",
            "from login — boss loot, reagents, and token",
            "data only load when you first hover a boss.",
            "",
            "|cffffd100Enjoy your transmog hunting!|r",
        },
    },
}

-- ============================================================================
-- CREATE FRAME
-- ============================================================================

local FRAME_WIDTH = 420
local FRAME_HEIGHT = 440
local LINE_HEIGHT = 16

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

    local f = CreateFrame("Frame", "ETBTutorialFrame", UIParent, "BackdropTemplate")
    f:SetSize(FRAME_WIDTH, FRAME_HEIGHT)
    f:SetPoint("CENTER", 0, 40)
    f:SetFrameStrata("DIALOG")
    f:SetFrameLevel(300)
    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)

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

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

    -- Title
    f.title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
    f.title:SetPoint("TOP", 0, -16)
    f.title:SetWidth(FRAME_WIDTH - 80)
    f.title:SetTextColor(1, 0.82, 0)

    -- Page indicator
    f.pageIndicator = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    f.pageIndicator:SetPoint("TOP", f.title, "BOTTOM", 0, -4)
    f.pageIndicator:SetTextColor(0.5, 0.5, 0.5)

    -- Content area
    f.content = CreateFrame("Frame", nil, f)
    f.content:SetPoint("TOPLEFT", 24, -58)
    f.content:SetPoint("BOTTOMRIGHT", -24, 70)

    -- Pre-create line fontstrings
    f.lines = {}
    for i = 1, 25 do
        local line = f.content:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
        line:SetPoint("TOPLEFT", 0, -(i - 1) * LINE_HEIGHT)
        line:SetWidth(FRAME_WIDTH - 52)
        line:SetJustifyH("LEFT")
        line:SetWordWrap(true)
        line:Hide()
        f.lines[i] = line
    end

    -- Bottom bar
    local bottomBar = CreateFrame("Frame", nil, f)
    bottomBar:SetPoint("BOTTOMLEFT", 16, 12)
    bottomBar:SetPoint("BOTTOMRIGHT", -16, 12)
    bottomBar:SetHeight(50)

    -- Previous button
    f.prevBtn = CreateFrame("Button", nil, bottomBar, "UIPanelButtonTemplate")
    f.prevBtn:SetSize(90, 24)
    f.prevBtn:SetPoint("BOTTOMLEFT", 8, 24)
    f.prevBtn:SetText("Previous")
    f.prevBtn:SetScript("OnClick", function() TUT:PrevPage() end)

    -- Next button
    f.nextBtn = CreateFrame("Button", nil, bottomBar, "UIPanelButtonTemplate")
    f.nextBtn:SetSize(90, 24)
    f.nextBtn:SetPoint("BOTTOMRIGHT", -8, 24)
    f.nextBtn:SetText("Next")
    f.nextBtn:SetScript("OnClick", function() TUT:NextPage() end)

    -- Page dots
    f.dots = {}
    local dotsFrame = CreateFrame("Frame", nil, bottomBar)
    dotsFrame:SetPoint("BOTTOM", 0, 28)
    dotsFrame:SetSize(#PAGES * 16, 12)
    f.dotsFrame = dotsFrame
    for i = 1, #PAGES do
        local dot = dotsFrame:CreateTexture(nil, "OVERLAY")
        dot:SetSize(8, 8)
        dot:SetPoint("LEFT", (i - 1) * 16, 0)
        dot:SetTexture("Interface\\COMMON\\Indicator-Gray")
        f.dots[i] = dot
    end

    -- Don't show again checkbox
    f.disableCheck = CreateFrame("CheckButton", nil, bottomBar, "UICheckButtonTemplate")
    f.disableCheck:SetSize(22, 22)
    f.disableCheck:SetPoint("BOTTOMLEFT", 8, 0)
    f.disableCheck:SetScript("OnClick", function(self)
        ETB_Settings = ETB_Settings or {}
        ETB_Settings.tutorialDismissed = self:GetChecked() and true or false
    end)

    f.disableLabel = bottomBar:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    f.disableLabel:SetPoint("LEFT", f.disableCheck, "RIGHT", 2, 0)
    f.disableLabel:SetText("Don't show on login")
    f.disableLabel:SetTextColor(0.6, 0.6, 0.6)

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

-- ============================================================================
-- PAGE RENDERING
-- ============================================================================

function TUT:ShowPage(pageNum)
    if not self.frame then self:Create() end
    local f = self.frame

    pageNum = math.max(1, math.min(pageNum, #PAGES))
    self.currentPage = pageNum
    local page = PAGES[pageNum]

    -- Title
    f.title:SetText(page.title)
    f.pageIndicator:SetText("Page " .. pageNum .. " of " .. #PAGES)

    -- Content lines
    for i = 1, 25 do
        f.lines[i]:Hide()
    end
    for i, text in ipairs(page.lines) do
        if f.lines[i] then
            f.lines[i]:SetText(text)
            f.lines[i]:Show()
        end
    end

    -- Update dots
    for i = 1, #PAGES do
        if i == pageNum then
            f.dots[i]:SetTexture("Interface\\COMMON\\Indicator-Yellow")
            f.dots[i]:SetSize(10, 10)
        else
            f.dots[i]:SetTexture("Interface\\COMMON\\Indicator-Gray")
            f.dots[i]:SetSize(8, 8)
        end
    end

    -- Button states
    f.prevBtn:SetEnabled(pageNum > 1)
    if pageNum < #PAGES then
        f.nextBtn:SetText("Next")
    else
        f.nextBtn:SetText("Finish")
    end

    -- Checkbox state
    ETB_Settings = ETB_Settings or {}
    f.disableCheck:SetChecked(ETB_Settings.tutorialDismissed or false)

    f:Show()
end

function TUT:NextPage()
    if self.currentPage >= #PAGES then
        self.frame:Hide()
    else
        self:ShowPage(self.currentPage + 1)
    end
end

function TUT:PrevPage()
    if self.currentPage > 1 then
        self:ShowPage(self.currentPage - 1)
    end
end

function TUT:Toggle()
    if self.frame and self.frame:IsShown() then
        self.frame:Hide()
    else
        self:ShowPage(1)
    end
end

-- ============================================================================
-- AUTO-SHOW ON FIRST LOGIN
-- ============================================================================

local initFrame = CreateFrame("Frame")
initFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
initFrame:SetScript("OnEvent", function(self, event)
    self:UnregisterEvent("PLAYER_ENTERING_WORLD")
    C_Timer.After(3, function()
        ETB_Settings = ETB_Settings or {}
        if not ETB_Settings.tutorialDismissed then
            TUT:ShowPage(1)
        end
    end)
end)
