--[[
============================================================
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 AchievementRows:|r constants are missing.")
    return
end

function dv.CreateAchievementHeader(parent, achievement, y, completed, total)
    completed = tonumber(completed) or 0
    total     = tonumber(total) or 0

    local headerName
    if type(achievement) == "string" then
        headerName = achievement
    elseif type(achievement) == "table" and achievement.name then
        headerName = achievement.name
    else
        headerName = "Unknown Category"
    end

    local collapseKey = "ach_" .. headerName

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

    local collapsed = dv.collapsedHeaders[collapseKey]

    if dv.filtersJustChanged then
        local groupSel = dv.filters.achievements.groups

        if not groupSel[headerName] then
            dv.collapsedHeaders[collapseKey] = true
            collapsed = true
        end
    end

    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(headerName 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("achievements", collapseKey)
end)

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

function dv.UpdateAchievementPreview(achievement)
    if not achievement 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
	dv.modelTitle:ClearAllPoints()
	dv.modelTitle:SetPoint("TOPLEFT", dv.modelDivider, "BOTTOMLEFT", 0, -6)
	dv.modelTitle:SetPoint("TOPRIGHT", dv.modelDivider, "BOTTOMRIGHT", 0, -6)

	dv.modelTitle:SetText(achievement.title or "Achievement Preview")
	dv.modelTitle:SetTextColor(1, 1, 1)
	dv.modelTitle:Show()

    -- =========================
    -- MODEL / TEXTURE
    -- =========================
if achievement.model3D then
    if texture then texture:Hide() end

    ms:Show()

    -- reset lock
    ms._cameraLocked = nil

    dv:ShowModel(ms, achievement.model3D)

    if not ms._cameraLocked then
        ms._cameraLocked = true

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

            -- 🎯 For OBJECTS (achievements), DO NOT use TargetActor
            if camera.SetTarget then
                camera:SetTarget(0, 0, 0)
            end

            -- 🔥 Use orbit zoom properly
            if camera.SetZoomDistance then
                camera:SetZoomDistance(4.5)
            end

            -- slight tilt
            if camera.SetPitch then
                camera:SetPitch(0.1)
            end
        end)
    end

    elseif achievement.texture then
        ms:Hide()

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

    -- =========================
    -- WOWHEAD WRAPPER
    -- =========================
    if not dv.achievementWowheadWrapper then
        dv.achievementWowheadWrapper = CreateFrame("Frame", nil, dv.itemContainer, "BackdropTemplate")
        local wrapper = dv.achievementWowheadWrapper

        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(0.6, 0.4, 1, 1)
        wrapper:SetHeight(28)

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

        dv.achievementWowheadBox = CreateFrame("EditBox", nil, wrapper, "InputBoxTemplate")
        local box = dv.achievementWowheadBox
        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

    dv.achievementWowheadWrapper:ClearAllPoints()
	dv.achievementWowheadWrapper:SetPoint("TOPLEFT", dv.modelTitle, "BOTTOMLEFT", 0, -6)
	dv.achievementWowheadWrapper:SetPoint("TOPRIGHT", dv.modelTitle, "BOTTOMRIGHT", 0, -6)
    dv.achievementWowheadBox:SetText("https://www.wowhead.com/achievement=" .. achievement.id)
    dv.achievementWowheadWrapper:Show()
end

function dv.CreateAchievementLine(parent, achievement, y)
    local id = achievement.id
    local isCompleted = dv.IsAchievementComplete(id)
    if isCompleted and vendorSettings.hideCompletedThings and not vendorSettings.markCompletedThings then
        return y
    end

    local name = select(2, GetAchievementInfo(id)) or "Unknown Achievement"

    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)

    line.text = line:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    line.text:SetPoint("LEFT", line.factionIcon, "RIGHT", 4, 0)
    line.text:SetFont(STANDARD_TEXT_FONT, 14)
    line.text:SetText(name)
	
	-- 🔥 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

	-- 🔥 FACTION ICON LOGIC
	local f = achievement.faction and string.lower(achievement.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 then
        if vendorSettings.markCompletedThings then
            -- ✅ greyed out
            line.text:SetTextColor(0.62, 0.62, 0.62)
            line.text:SetAlpha(0.7)
        else
            -- ✅ use faction color even if completed
            if achievement.faction then
                local f = string.lower(achievement.faction)
                local color = (f == "alliance" and C.COLORS.ALLIANCE) or 
                              (f == "horde" and C.COLORS.HORDE) or 
                              (f == "neutral" and C.COLORS.NEUTRAL)

                line.text:SetTextColor(unpack(color or {0.9, 0.9, 0.9}))
            else
                line.text:SetTextColor(0.9, 0.9, 0.9)
            end

            line.text:SetAlpha(1)
        end
    else
        -- ❌ not completed → normal faction coloring
        if achievement.faction then
            local f = string.lower(achievement.faction)
            local color = (f == "alliance" and C.COLORS.ALLIANCE) or 
                          (f == "horde" and C.COLORS.HORDE) or 
                          (f == "neutral" and C.COLORS.NEUTRAL)

            line.text:SetTextColor(unpack(color or {0.9, 0.9, 0.9}))
        else
            line.text:SetTextColor(0.9, 0.9, 0.9)
        end

        line.text:SetAlpha(1)
    end
end
    SetBaseColor()

    line:SetScript("OnEnter", function()
        line.text:SetTextColor(unpack(C.COLORS.GOLD))
        GameTooltip:SetOwner(line, "ANCHOR_LEFT")
        GameTooltip:AddLine(" ")
        GameTooltip:AddLine("|cff00ff00<Left Click>|r Open Achievement")
        GameTooltip:AddLine("|cff00ff00<Left Click>|r View Decor Item")
        GameTooltip:AddLine("|cffff5500<Left Click>|r Copy Wowhead Link")
        GameTooltip:Show()
    end)

    line:SetScript("OnClick", function(_, button)
        if button == "LeftButton" then
            -- ✅ Calling the external Logic function
            dv.UpdateAchievementPreview(achievement)

            if vendorSettings.openAchievementFrame then
                if not AchievementFrame or not AchievementFrame:IsShown() then
                    AchievementFrame_LoadUI()
                    AchievementFrame_ToggleAchievementFrame()
                end
                AchievementFrame_SelectAchievement(id)
            end

            if dv.achievementWowheadBox then
                dv.achievementWowheadBox:HighlightText()
            end
        end
    end)

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

    table.insert(dv.activeWidgets, line)
    return y - 22
end
