-- Book-Quests.lua -- The book has plans of its own sometimes --
-- WanderBook: Forge your path through Azeroth with your own goals. --
-- Made by Blakmane. May 2025. --

local _, addon = ...
WanderBook = addon

--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------

-- Only show if not yet unlocked (check saved variable)
if WanderBook_UnlockState == nil or not WanderBook_UnlockState.unlocked then
    C_Timer.After(2, function()
        if not (WanderBook_UnlockState and WanderBook_UnlockState.unlocked) then
            ShowWanderBookUnlockQuest()
        end
    end)
end

-- INITIAL QUEST --
function ShowWanderBookUnlockQuest()
    if _G["WanderBookUnlockFrame"] and _G["WanderBookUnlockFrame"]:IsShown() then
        return -- Already showing
    elseif _G["WanderBookUnlockFrame"] then
        _G["WanderBookUnlockFrame"]:Show()
        return
    end
    PlaySound(SOUNDKIT.UI_QUEST_ROLLING_FORWARD_01, "SFX")
    local f = CreateFrame("Frame", "WanderBookUnlockFrame", UIParent)
    f:SetSize(370, 550)  -- You can tweak size
    f:SetPoint("CENTER", UIParent, "CENTER", 350, 50)
    f:SetFrameStrata("DIALOG")

    local bg = f:CreateTexture(nil, "BACKGROUND")
    bg:SetAtlas("AdventureMapQuest-QuestPane")
    bg:SetAllPoints(f)
    bg:SetTexCoord(0, 1, 0, 1)

    f.title = f:CreateFontString(nil, "OVERLAY", nil)
    f.title:SetFont("Fonts\\FRIZQT__.TTF", 16, "")
    f.title:SetTextColor(0.30, 0.1, 0)
    f.title:SetPoint("TOP", -3, -105)
    f.title:SetText("Forgotten Dwarven Note")
    
    -- Decorative Divider
    local divider = f:CreateTexture(nil, "ARTWORK")
    divider:SetAtlas("thewarwithin-scenario-line-bottom")
    divider:SetSize(200, 2)
    divider:SetPoint("TOP", 0, -135)
    divider:SetAlpha(0.3)

    f.body = f:CreateFontString(nil, "OVERLAY", nil)
    f.body:SetFont("Fonts\\FRIZQT__.TTF", 12, "")
    f.body:SetTextColor(0.30, 0.1, 0)
    f.body:SetPoint("TOPLEFT", 55, -155)
    f.body:SetJustifyH("LEFT")
    f.body:SetWidth(260) -- This will now be respected
    f.body:SetText("You rummage through your bags and stumble upon a scrap of parchment that wasn’t there before. The faded paper hums faintly with warmth.\n\nSketched upon it are dwarven runes — old, cryptic, and scorched at the edges. Alongside them, a rough sketch of a tome bound in iron, with a strange symbol etched into its cover.\n\nAt the bottom, the hand writting reads:\n\n\'Made by request of a Gilnean friend. Tell the courrier to leave it at his usual hideout north of Utgarde, in Howling Fjord.'")

    -- Icon + Reward name
    local iconBtn = CreateFrame("Button", nil, f)
    iconBtn:SetSize(45, 45)
    iconBtn:SetPoint("BOTTOMLEFT", 100, 120)
    iconBtn:SetNormalTexture(1505932)
    iconBtn:SetHighlightTexture("Interface\\Buttons\\ButtonHilight-Square")

    local border = iconBtn:CreateTexture(nil, "OVERLAY")
    border:SetSize(55, 55)
    border:SetPoint("CENTER", iconBtn, "CENTER")
    border:SetTexture("Interface\\AddOns\\WanderBook\\Media\\slot-icon-border-silver.tga")
    
iconBtn:SetScript("OnClick", function()
        PlaySound(SOUNDKIT.IG_ABILITY_PAGE_TURN)
    if f.noteImage and f.noteImage:IsShown() then
        f.noteImage:Hide()
        return
    end

    if not f.noteImage then
        local note = CreateFrame("Frame", nil, f)
        note:SetSize(300, 300)
        note:SetPoint("TOPRIGHT", f, "TOPLEFT", 40, -130)

        local tex = note:CreateTexture(nil, "ARTWORK")
        tex:SetAllPoints(note)
        tex:SetTexture("Interface\\AddOns\\WanderBook\\Media\\note.tga") -- Replace with your note image
        f.noteImage = note
    end

    f.noteImage:Show()
end)


    local rewardText = f:CreateFontString(nil, "OVERLAY", nil)
    rewardText:SetFont("Fonts\\FRIZQT__.TTF", 14, "")
    rewardText:SetTextColor(1, 1, 1)
    rewardText:SetPoint("LEFT", iconBtn, "RIGHT", 18, 0)
    rewardText:SetText("Mysterious\nDwarven Note")
    
    --item bg
    local itembg = f:CreateTexture(nil, "ARTWORK")
    itembg:SetAtlas("thewarwithin-scenario-frame")
    itembg:SetSize(210, 75)
    itembg:SetPoint("BOTTOM", 0, 105)
    --itembg:SetAlpha(0.7)
    
    local skipText = f:CreateFontString(nil, "OVERLAY", nil)
    skipText:SetFont("Fonts\\FRIZQT__.TTF", 10, "")
    skipText:SetTextColor(0.5, 0.3, 0)
    skipText:SetPoint("CENTER", 0, -180)
    skipText:SetText("Skip intro with /wbskip")

    -- Accept button
    local acceptBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
    acceptBtn:SetSize(100, 25)
    acceptBtn:SetPoint("BOTTOM", 0, 43)
    acceptBtn:SetText("Accept")

    acceptBtn:SetScript("OnClick", function()
        f:Hide()
        C_Timer.After(1, function()
            RaidNotice_AddMessage(RaidBossEmoteFrame, "|cfffe35eeWhat could be north of Utgarde in Howling Fjord besides Winterskorn Vrykul?|r", ChatTypeInfo["RAID_WARNING"])
        end)
        print("|cfffe35eeWhat could be north of Utgarde in Howling Fjord\nbesides Winterskorn Vrykul?.|r")
        PlaySound(SOUNDKIT.UI_WORLDQUEST_START, "SFX")

        -- Begin tracking player zone and coordinates after accepting
        C_Timer.NewTicker(1, function()
            if WanderBook.unlocked then return end

            local mapID = C_Map.GetBestMapForUnit("player")
            if not mapID then return end

            local mapInfo = C_Map.GetMapInfo(mapID)
            if not mapInfo or mapInfo.name ~= "Howling Fjord" then return end

            local pos = C_Map.GetPlayerMapPosition(mapID, "player")
            if not pos then return end

            local x, y = pos:GetXY()
            
            -- QUEST CONDITIONS --

            local subzone = GetMinimapZoneText()

            -- Breadcrumb A: Only fire when entering "North Spear Tower" and not already inside or fully unlocked
            if subzone == "North Spear Tower" and WanderBook.lastZone ~= subzone and not WanderBook.breadcrumbB then
                --PlaySound(SOUNDKIT.UI_SCENARIO_STAGE_END, "SFX")
                PlaySound(SOUNDKIT.UI_BONUS_EVENT_SYSTEM_VIGNETTES, "Master")
                C_Timer.After(1, function()
                    RaidNotice_AddMessage(RaidBossEmoteFrame, "|cfffe35eeSomething hums inside that old wooden tower...|r", ChatTypeInfo["RAID_WARNING"])
                end)
                print("|cfffe35eeSomething hums inside that old wooden tower...|r")
                WanderBook.lastZone = subzone
            end

            -- Track when we leave the subzone
            if subzone ~= WanderBook.lastZone and WanderBook.lastZone == "North Spear Tower" then
                --PlaySound(SOUNDKIT.UI_SCENARIO_STAGE_END, "SFX")
                WanderBook.lastZone = subzone -- reset for re-entry
            end

            -- Breadcrumb B: Loose coordinate
            if math.abs(x - 0.5430) <= 0.001 and math.abs(y - 0.2307) <= 0.001 and not WanderBook.breadcrumbB then
                PlaySound(SOUNDKIT.UI_QUEST_ROLLING_FORWARD_01, "SFX")
                WanderBook.breadcrumbB = true
                local msg = "|cfffe35eeWhat's in those dusty shelves?|r"
                C_Timer.After(1, function()
                    RaidNotice_AddMessage(RaidBossEmoteFrame, msg, ChatTypeInfo["RAID_WARNING"])
                    C_Timer.After(3, function()  -- hide after 1.5 seconds
                        RaidNotice_Clear(RaidBossEmoteFrame)
                    end)
                end)
                print("|cfffe35eeWhat's in those dusty shelves?|r")
            end
    
            if math.abs(x - 0.5415) <= 0.0004 and math.abs(y - 0.2263) <= 0.0004 then
                if not IsIndoors() then
                    --print("You must be indoors to reach the WanderBook.")
                    return
                end

                if IsMounted() then
                    --print("Dismount to uncover the WanderBook.")
                    return
                end

                if not WanderBook.rewardPopupShown then
                C_Timer.After(1, function()
                    RaidNotice_AddMessage(RaidBossEmoteFrame, "|cfffe35eeThat's one fancy looking book.|r", ChatTypeInfo["RAID_WARNING"])
                end)
                    PlaySound(SOUNDKIT.UI_WORLDQUEST_COMPLETE, "SFX")
                    WanderBook.rewardPopupShown = true
                    ShowWanderBookRewardPopup()
                    --print("|cff00ff00You discovered the source of the call. WanderBook is now unlocked!|r")
                end
            end
        end)
    end)
end

-- COMPLETED QUEST --
function ShowWanderBookRewardPopup()
    local rewardFrame = CreateFrame("Frame", "WanderBookUnlockFrame", UIParent)
    rewardFrame:SetSize(370, 550)  -- You can tweak size
    rewardFrame:SetPoint("CENTER", UIParent, "CENTER", 350, 50)
    rewardFrame:SetFrameStrata("DIALOG")

    local bg = rewardFrame:CreateTexture(nil, "BACKGROUND")
    bg:SetAtlas("AdventureMapQuest-QuestPane")
    bg:SetAllPoints(rewardFrame)
    bg:SetTexCoord(0, 1, 0, 1)
    
    rewardFrame.title = rewardFrame:CreateFontString(nil, "OVERLAY", nil)
    rewardFrame.title:SetFont("Fonts\\FRIZQT__.TTF", 16, "")
    rewardFrame.title:SetTextColor(0.30, 0.1, 0)
    rewardFrame.title:SetPoint("TOP", -3, -105)
    rewardFrame.title:SetText("The Strange Tome")
    
    -- Decorative Divider
    local divider = rewardFrame:CreateTexture(nil, "ARTWORK")
    divider:SetAtlas("thewarwithin-scenario-line-bottom")
    divider:SetSize(200, 2)
    divider:SetPoint("TOP", 0, -135)
    divider:SetAlpha(0.3)

    rewardFrame.body = rewardFrame:CreateFontString(nil, "OVERLAY", nil)
    rewardFrame.body:SetFont("Fonts\\FRIZQT__.TTF", 12, "")
    rewardFrame.body:SetTextColor(0.30, 0.1, 0)
    rewardFrame.body:SetPoint("TOPLEFT", 55, -155)
    rewardFrame.body:SetJustifyH("LEFT")
    rewardFrame.body:SetWidth(260)
    rewardFrame.body:SetText("At last, the source of the call lies before you. The book’s surface thrums with arcane resonance — an echo of forgotten oaths sealed in silence, now awaiting your intent.\n\nEtched into its bindings are faint Dwarven notations, reinforced with Kaldorei enchantments that shimmer faintly beneath the surface. There’s a strange scent clinging to the cover — damp earth, arcane oil... and perhaps, the lingering trace of wet dog.\n\nClearly, this tome once passed through Gilnean hands. Reach out and claim it.")
    
    -- Flavor text above the icon
--[[    local flavorText = rewardFrame:CreateFontString(nil, "OVERLAY", nil)
    flavorText:SetFont("Fonts\\FRIZQT__.TTF", 14, "")
    flavorText:SetTextColor(0.30, 0.1, 0)
    flavorText:SetPoint("BOTTOM", 0, 200)
    flavorText:SetWidth(240)
    flavorText:SetJustifyH("CENTER")
    flavorText:SetText("Reach out and claim it.")]]

    local iconBtn = CreateFrame("Button", nil, rewardFrame)
    iconBtn:SetSize(64, 64)
    iconBtn:SetPoint("BOTTOM", 0, 125)
    iconBtn:SetNormalTexture(4624873)  -- Book icon
    iconBtn:SetHighlightTexture("Interface\\Buttons\\ButtonHilight-Square")

    local btnBorder = iconBtn:CreateTexture(nil, "OVERLAY")
    btnBorder:SetSize(72, 72)
    btnBorder:SetPoint("CENTER", iconBtn, "CENTER")
    btnBorder:SetTexture("Interface\\AddOns\\WanderBook\\Media\\slot-icon-border-silver.tga")

    --item bg
    local itembg = rewardFrame:CreateTexture(nil, "ARTWORK")
    itembg:SetAtlas("spellbook-item-iconframe-inactive")
    itembg:SetSize(110, 105)
    itembg:SetPoint("BOTTOM", -8, 100)
    --itembg:SetAlpha(1)

    iconBtn:SetScript("OnClick", function()
        rewardFrame:Hide()
        WanderBook.unlocked = true
        WanderBook_UnlockState.unlocked = true
        C_Timer.After(1, function()
            RaidNotice_AddMessage(RaidBossEmoteFrame, "|cfffe35eeThe WanderBook is now in your possession.\nUse /wb to open it. May your oaths never break.|r", ChatTypeInfo["RAID_WARNING"])
        end)
        print("|cfffe35eeThe WanderBook is now in your possession. Use /wb to open it. May your oaths never break.|r")
        ShowWanderBookTooltip()
    end)
end

function ShowWanderBookTooltip()
    PlaySound(SOUNDKIT.UI_WARFORGED_ITEM_LOOT_TOAST, "SFX")
    local tooltip = CreateFrame("Frame", nil, UIParent, "TooltipBorderedFrameTemplate")
    tooltip:SetSize(170, 180)
    tooltip:SetPoint("CENTER", 0, -100)
    tooltip:SetFrameStrata("TOOLTIP")
    tooltip:ClearAllPoints()
    tooltip:SetPoint("CENTER", UIParent, "CENTER", 0, 0)

    -- Close button
    local closeBtn = CreateFrame("Button", nil, tooltip, "UIPanelCloseButton")
    closeBtn:SetPoint("TOPRIGHT", 0, 0)
    closeBtn:SetScript("OnClick", function()
        PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_OFF, "SFX")
        tooltip:Hide()
    end)

    local lines = {
        { text = "The WanderBook", color = ITEM_QUALITY_COLORS[4], style = "GameTooltipHeaderText" }, -- Epic
        { text = "Soulbound", color = {r=1, g=1, b=1} },
        { text = "Relic", color = {r=1, g=1, b=1} },
        { text = "+35 Insight", color = {r=1, g=1, b=1} },
        { text = "+81 Wanderlust", color = {r=1, g=1, b=1} },
        { text = "+512 Courage", color = GREEN_FONT_COLOR },
        { text = "+242 Curiosity", color = GREEN_FONT_COLOR },
    }

    local yOffset = -10
    for i, line in ipairs(lines) do
        local style = line.style or "GameTooltipText"
        local fs = tooltip:CreateFontString(nil, "OVERLAY", style)
        fs:SetPoint("TOPLEFT", 10, yOffset)
        fs:SetText(line.text)
        fs:SetTextColor(line.color.r, line.color.g, line.color.b)
        yOffset = yOffset - 15  -- tighter spacing
    end

    -- Flavor text (wraps)
    local flavor = tooltip:CreateFontString(nil, "OVERLAY", "GameTooltipText")
    flavor:SetPoint("TOPLEFT", 10, yOffset - 2)
    flavor:SetPoint("RIGHT", -10, 0)
    flavor:SetJustifyH("LEFT")
    flavor:SetTextColor(1, 0.82, 0)
    flavor:SetText("\"This silent book brims with potential, open it with /wb and forge your own path with it.\"")
end

SLASH_WBSKIPINTRO1 = "/wbskip"
SlashCmdList["WBSKIPINTRO"] = function()
    -- Hide intro frame if open
    PlaySound(SOUNDKIT.UI_WORLDQUEST_COMPLETE, "SFX")
    if _G["WanderBookUnlockFrame"] and _G["WanderBookUnlockFrame"]:IsShown() then
        _G["WanderBookUnlockFrame"]:Hide()
    end

    -- Mark breadcrumbs as complete so they don't trigger again
    WanderBook.breadcrumbB = true
    WanderBook.rewardPopupShown = true

    -- Show the reward popup
    ShowWanderBookRewardPopup()
end

