--[[
============================================================
Decor Vendor Addon
© 2026 MidniteDestiny. All Rights Reserved.
============================================================

This file is part of the Decor Vendor addon.

All code, structure, and design are the intellectual
property of MidniteDestiny unless otherwise stated.

You may NOT:
• Copy, reproduce, or redistribute this code
• Modify and redistribute this code
• Use this code in other addons or projects

without explicit permission from the author.

This addon is distributed for personal use only.

============================================================
]]

local addonName, dv = ...

local C = dv.CONSTANTS

if not C then
    print("|cffff4040DecorVendor QuestRows:|r constants are missing.")
    return
end

function dv.CreateQuestHeader(parent, questGroup, y, completed, total)
    completed = tonumber(completed) or 0
    total     = tonumber(total) or 0

    local groupName = questGroup.name or tostring(questGroup)

    local collapseKey = "quest_" .. groupName

    if dv.collapsedHeaders[collapseKey] == nil then
        dv.collapsedHeaders[collapseKey] = true
    end

    if dv.filtersJustChanged then
        local expSel = dv.filters.quests.expansions

        if not expSel[groupName] then
            dv.collapsedHeaders[collapseKey] = true
            collapsed = true
        end
    end

    local collapsed = dv.collapsedHeaders[collapseKey]

    local header = CreateFrame("Button", nil, parent)
    header:SetPoint("TOPLEFT", parent, "TOPLEFT", 0, y)
    header:SetPoint("RIGHT", parent, "RIGHT", -6, 0)
    header:SetHeight(C.VENDOR_HEADER_HEIGHT)

    local bg = header:CreateTexture(nil, "BACKGROUND")
    bg:SetAllPoints()
    bg:SetTexture("Interface\\Buttons\\WHITE8x8")
    bg:SetGradient("HORIZONTAL",
        CreateColor(0.15, 0.10, 0.25, 0.9),
        CreateColor(0.05, 0.05, 0.15, 0.9)
    )

    header.icon = header:CreateFontString(nil, "OVERLAY")
    header.icon:SetFont(STANDARD_TEXT_FONT, 13)
    header.icon:SetPoint("LEFT", 10, 0)
    header.icon:SetText(collapsed and "+" or "-")

    header.text = header:CreateFontString(nil, "OVERLAY")
    header.text:SetFont(STANDARD_TEXT_FONT, 12,"OUTLINE")
    header.text:SetPoint("LEFT", 20, 0)
    header.text:SetText(string.format(groupName or "Unknown", completed, total))

    header.progress = header:CreateFontString(nil, "OVERLAY")
    header.progress:SetFont(STANDARD_TEXT_FONT, 12,"OUTLINE")
    header.progress:SetPoint("RIGHT", -8, 0)
    header.progress:SetText(string.format("%d/%d completed", completed, total))

    local color
    if total > 0 and completed == total then
        color = CreateColor(0.2, 1, 0.2, 1)
    elseif completed >= total / 2 then
        color = CreateColor(1, 0.82, 0, 1)
    else
        color = CreateColor(0.9, 0.9, 0.9, 1)
    end
    header.progress:SetTextColor(color:GetRGBA())

header:SetScript("OnClick", function()
    dv.ToggleAccordionHeader("quests", collapseKey)
end)

    table.insert(dv.activeWidgets, header)
    return collapsed, y - 26
end

function dv.CreateQuestLine(parent, quest, y)
    local id = quest.id
    local isCompleted = dv.IsQuestEffectivelyCompleted(quest)

    if isCompleted and vendorSettings.hideCompletedThings and not vendorSettings.markCompletedThings then
        return y
    end

    local liveTitle = dv.questTitleCache[id] or C_QuestLog.GetTitleForQuestID(id)
    local name
    local loading = false

    if liveTitle and liveTitle ~= "" then
        name = liveTitle
        dv.questTitleCache[id] = liveTitle
    else
        name = quest.questName or "|cff888888Quest title unavailable|r"
        loading = not quest.questName
    end

    local line = CreateFrame("Button", nil, parent)
    line:SetPoint("TOPLEFT", parent, "TOPLEFT", 10, y)
    line:SetPoint("RIGHT", parent, "RIGHT", -6, 0)
    line:SetHeight(C.LINE_HEIGHT)
    line:RegisterForClicks("AnyUp")

    -- 🔥 STATUS ICON
    line.statusIcon = line:CreateTexture(nil, "OVERLAY")
    line.statusIcon:SetSize(16, 16)
    line.statusIcon:SetPoint("LEFT", 0, 0)

    -- 🔥 FACTION ICON
    line.factionIcon = line:CreateTexture(nil, "OVERLAY")
    line.factionIcon:SetSize(16, 16)
    line.factionIcon:SetPoint("LEFT", line.statusIcon, "RIGHT", 2, 0)

    -- 🔥 STATUS ICON LOGIC
    if isCompleted then
        line.statusIcon:SetTexture("Interface\\Buttons\\UI-CheckBox-Check")
        line.statusIcon:SetVertexColor(0.2, 1, 0.2)
        line.statusIcon:SetAlpha(0.9)
        line.statusIcon:Show()
    else
        line.statusIcon:SetTexture("Interface\\Buttons\\UI-GroupLoot-Pass-Up")
        line.statusIcon:SetVertexColor(1, 0.2, 0.2)
        line.statusIcon:SetAlpha(0.75)
        line.statusIcon:Show()
    end

    line.text = line:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    line.text:SetPoint("LEFT", line.factionIcon, "RIGHT", 4, 0)
    line.text:SetFont(STANDARD_TEXT_FONT, 13, "OUTLINE")
    line.text:SetText(name)

    -- 🔥 FACTION ICON LOGIC
    local f = quest.faction and string.lower(quest.faction)

    if f == "alliance" then
        line.factionIcon:SetTexture("Interface\\AddOns\\DecorVendor\\Assets\\blue")
    elseif f == "horde" then
        line.factionIcon:SetTexture("Interface\\AddOns\\DecorVendor\\Assets\\red")
    elseif f == "neutral" then
        line.factionIcon:SetTexture("Interface\\AddOns\\DecorVendor\\Assets\\neutral")
    else
        line.factionIcon:Hide()
    end

    line.factionIcon:SetAlpha(0.9)

    local function SetBaseColor()
        if isCompleted and vendorSettings.markCompletedThings then
            line.text:SetTextColor(0.62, 0.62, 0.62)
            line.text:SetAlpha(0.7)
            return
        end

        line.text:SetAlpha(1)

        if quest.faction then
            local f = string.lower(quest.faction)
            if f == "alliance" then
                line.text:SetTextColor(unpack(C.COLORS.ALLIANCE))
            elseif f == "horde" then
                line.text:SetTextColor(unpack(C.COLORS.HORDE))
            elseif f == "neutral" then
                line.text:SetTextColor(unpack(C.COLORS.NEUTRAL))
            end
        else
            line.text:SetTextColor(0.9, 0.9, 0.9)
        end
    end

    SetBaseColor()

    if loading then
        QuestEventListener:AddCallback(
            id,
            function()
                local newName = C_QuestLog.GetTitleForQuestID(id)
                if newName and line.text:IsVisible() then
                    line.text:SetText(newName)
                    dv.questTitleCache[id] = newName
                end
            end
        )
    end

    local function UpdateQuestPreview(quest)
        if not quest then
            return
        end

        local ms = dv.modelScene
        local actor = dv.previewActor
        local texture = dv.texture
        if not ms or not actor then
            return
        end

        dv.contentArea._isVendorPreview = false

        -- Title
        if dv.modelTitle then
            dv.modelTitle:SetText(quest.title or "Quest Preview")
            dv.modelTitle:SetTextColor(1, 1, 1)
        end

        -- 1. Wowhead Wrapper Logic (EditBox for easy copying)
        if not dv.questWowheadWrapper then
            dv.questWowheadWrapper = CreateFrame("Frame", nil, dv.itemContainer, "BackdropTemplate")
            local wrapper = dv.questWowheadWrapper
            wrapper:SetBackdrop(
                {
                    bgFile = "Interface\\Buttons\\WHITE8x8",
                    edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
                    edgeSize = 12,
                    insets = {left = 3, right = 3, top = 3, bottom = 3}
                }
            )
            wrapper:SetBackdropColor(0.08, 0.08, 0.12, 0.95)
            wrapper:SetBackdropBorderColor(1, 0.82, 0, 1)
            wrapper:SetHeight(28)

            wrapper.icon = wrapper:CreateTexture(nil, "ARTWORK")
            wrapper.icon:SetSize(18, 18)
            wrapper.icon:SetPoint("LEFT", wrapper, "LEFT", 6, 0)
            wrapper.icon:SetTexture("Interface\\Icons\\INV_Misc_Spyglass_03")

            dv.questWowheadBox = CreateFrame("EditBox", nil, wrapper, "InputBoxTemplate")
            local box = dv.questWowheadBox
            box:SetAutoFocus(false)
            box:SetHeight(22)
            box:SetPoint("LEFT", wrapper.icon, "RIGHT", 6, 0)
            box:SetPoint("RIGHT", wrapper, "RIGHT", -8, 0)
            box:SetScript(
                "OnMouseUp",
                function(self)
                    self:HighlightText()
                end
            )
        end

        -- Position Wowhead Box under the divider
        dv.questWowheadWrapper:ClearAllPoints()
        dv.questWowheadWrapper:SetPoint("TOPLEFT", dv.modelTitle, "BOTTOMLEFT", 0, -6)
        dv.questWowheadWrapper:SetPoint("TOPRIGHT", dv.modelTitle, "BOTTOMRIGHT", 0, -6)
        dv.questWowheadBox:SetText("https://www.wowhead.com/quest=" .. quest.id)
        dv.questWowheadWrapper:Show()

        -- 2. Quest Notes Logic
        if not dv.questNotes then
            dv.questNotes = CreateFrame("Frame", nil, dv.itemContainer)
            dv.questNotes.bg = dv.questNotes:CreateTexture(nil, "BACKGROUND")
            dv.questNotes.bg:SetAllPoints()
            dv.questNotes.bg:SetColorTexture(0.08, 0.08, 0.08, 0.75)
            dv.questNotes.text = dv.questNotes:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
            dv.questNotes.text:SetPoint("TOPLEFT", 10, -10)
            dv.questNotes.text:SetJustifyH("LEFT")
            dv.questNotes.text:SetWordWrap(true)
            dv.questNotes.text:SetFont(STANDARD_TEXT_FONT, 12, "")
        end

        dv.questNotes:ClearAllPoints()
        dv.questNotes:SetPoint("TOPLEFT", dv.questWowheadWrapper, "BOTTOMLEFT", 0, -6)
        dv.questNotes:SetPoint("TOPRIGHT", dv.questWowheadWrapper, "BOTTOMRIGHT", 0, -6)

        if quest.note then
            dv.questNotes.text:SetText("• " .. quest.note)
            local width = dv.itemContainer:GetWidth() - 20
            dv.questNotes.text:SetWidth(width - 20)
            dv.questNotes:SetHeight(dv.questNotes.text:GetStringHeight() + 20)
            dv.questNotes:Show()
        else
            dv.questNotes:Hide()
        end

        -- 3. Model / Texture Loading Logic
        if quest.vendorDisplayID then
            dv.contentArea._isVendorPreview = true
            if texture then
                texture:Hide()
            end

            ms:Show()

            -- ✅ FIXED
            dv:ShowModel(ms, nil, quest.vendorDisplayID)

            actor:SetAnimation(2)

            C_Timer.After(
                0.01,
                function()
                    local camera = ms:GetActiveCamera()
                    if not camera then
                        return
                    end

                    if camera.TargetActor then
                        camera:TargetActor(actor, true)
                    end
                end
            )
        elseif quest.model3D then
            if texture then
                texture:Hide()
            end

            ms:Show()

            -- ✅ FIXED
            dv:ShowModel(ms, quest.model3D)

            C_Timer.After(
                0.01,
                function()
                    local camera = ms:GetActiveCamera()
                    if not camera then
                        return
                    end

                    if camera.TargetActor then
                        camera:TargetActor(actor, true)
                    end

                    -- slight tilt for decor
                    if camera.SetPitch then
                        camera:SetPitch(0.2)
                    end
                end
            )
        elseif quest.texture then
            ms:Hide()

            if texture then
                texture:SetTexture(quest.texture)
                texture:Show()
            end
        else
            ms:Hide()
            if texture then
                texture:Hide()
            end
        end
    end

line:SetScript(
    "OnClick",
    function(_, button)
        if button == "LeftButton" then
            if dv.MarkPreviewContentShown then
                dv.MarkPreviewContentShown()
            elseif dv.HidePreviewEmptyState then
                dv.HidePreviewEmptyState()
            end

            UpdateQuestPreview(quest)

            if dv.questWowheadWrapper and dv.questWowheadBox then
                dv.questWowheadBox:SetText("https://www.wowhead.com/quest=" .. id)
                dv.questWowheadBox:HighlightText()
                dv.questWowheadWrapper:Show()
            end
        end
    end
)

    line:SetScript(
        "OnEnter",
        function()
            line.text:SetTextColor(unpack(C.COLORS.GOLD))

            GameTooltip:SetOwner(line, "ANCHOR_LEFT")
            GameTooltip:SetHyperlink("quest:" .. id)
            GameTooltip:AddLine("|cffff5500<Left Click>|r View Decor Item")
            GameTooltip:AddLine("|cffff5500<Left Click>|r Copy Wowhead Link")
            GameTooltip:Show()
        end
    )

    line:SetScript(
        "OnLeave",
        function()
            GameTooltip:Hide()
            SetBaseColor()
        end
    )

    table.insert(dv.activeWidgets, line)

    return y - 22
end
