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

function dv.CreateVendorHeader(parent, group, y, completed, total)
    completed = tonumber(completed) or 0
    total = tonumber(total) or 0

    if dv.collapsedHeaders[group.name] == nil then
        dv.collapsedHeaders[group.name] = true
    end

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

        if expSel[group.name] then
            dv.collapsedHeaders[group.name] = false
        else
            dv.collapsedHeaders[group.name] = true
        end
    end

    local header = CreateFrame("Button", nil, parent)
    header:SetPoint("TOPLEFT", parent, "TOPLEFT", 6, y)
    header:SetPoint("TOPRIGHT", parent, "TOPRIGHT", -10, y)
    header:SetHeight(C.VENDOR_HEADER_HEIGHT or 24)

    local bg = header:CreateTexture(nil, "BACKGROUND")
    bg:SetAllPoints()
    bg:SetTexture("Interface\\Buttons\\WHITE8x8")
    bg:SetColorTexture(0.10, 0.065, 0.17, 0.82)

    local accent = header:CreateTexture(nil, "ARTWORK")
    accent:SetPoint("LEFT", header, "LEFT", 2, 0)
    accent:SetSize(2, header:GetHeight() - 6)
    accent:SetColorTexture(0.75, 0.50, 1, 0.45)

    header.icon = header:CreateFontString(nil, "OVERLAY")
    header.icon:SetFont(STANDARD_TEXT_FONT, 12, "OUTLINE")
    header.icon:SetPoint("LEFT", header, "LEFT", 10, 0)

    if dv.collapsedHeaders[group.name] then
        header.icon:SetText("+")
    else
        header.icon:SetText("-")
    end

    header.icon:SetTextColor(0.92, 0.86, 1)

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

    if total > 0 and completed == total then
        header.progress:SetTextColor(0.4, 1, 0.4)

    elseif total > 0 and completed >= total / 2 then
        header.progress:SetTextColor(1, 0.85, 0.3)

    else
        header.progress:SetTextColor(0.75, 0.75, 0.75)
    end

    header.text = header:CreateFontString(nil, "OVERLAY")
    header.text:SetFont(STANDARD_TEXT_FONT, 12, "OUTLINE")
    header.text:SetPoint("LEFT", header.icon, "RIGHT", 8, 0)
    header.text:SetPoint("RIGHT", header.progress, "LEFT", -8, 0)
    header.text:SetJustifyH("LEFT")
    header.text:SetText(group.name or "Unknown")
    header.text:SetTextColor(0.95, 0.92, 1)
    header.text:SetNonSpaceWrap(false)
    header.text:SetWordWrap(false)

    header:SetScript("OnEnter", function()
        bg:SetColorTexture(0.16, 0.10, 0.26, 0.95)
        accent:SetColorTexture(1, 0.78, 0.28, 0.8)
    end)

    header:SetScript("OnLeave", function()
        bg:SetColorTexture(0.10, 0.065, 0.17, 0.82)
        accent:SetColorTexture(0.75, 0.50, 1, 0.45)
    end)

header:SetScript("OnClick", function()
    dv.ToggleAccordionHeader("vendors", group.name)
end)

    table.insert(dv.activeWidgets, header)

    return header, dv.collapsedHeaders[group.name], y - (C.VENDOR_HEADER_HEIGHT or 24)
end

function dv.CreateVendorLine(parent, vendor, y)

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

	-- 🔥 STATUS ICON (Found / Not Found)
	local icon = line:CreateTexture(nil, "OVERLAY")
	icon:SetSize(14, 14)
	icon:SetPoint("LEFT", 0, 0)

    -- 🔥 FACTION ICON
    line.factionIcon = line:CreateTexture(nil, "OVERLAY")
    line.factionIcon:SetSize(16, 16)
    line.factionIcon:SetPoint("LEFT", icon, "RIGHT", 2, 0)
	
    local text = line:CreateFontString(nil, "OVERLAY")
    text:SetFont(STANDARD_TEXT_FONT, 12,"OUTLINE")
    text:SetPoint("LEFT", line.factionIcon, "RIGHT", 4, 0)
    text:SetText(vendor.title or "Unknown Vendor")

    local isFound =
        vendorSettings.visited
        and vendorSettings.visited[vendor.id]

	-- 🔥 ICON LOGIC
	if isFound then
    icon:SetTexture("Interface\\Buttons\\UI-CheckBox-Check")
    icon:SetVertexColor(0.2, 1, 0.2)
    icon:SetAlpha(0.9)
	else
    icon:SetTexture("Interface\\Buttons\\UI-GroupLoot-Pass-Up")
    icon:SetVertexColor(1, 0.2, 0.2)
    icon:SetAlpha(0.75)
	end

    -- 🔥 FACTION ICON LOGIC
    local f = vendor.faction and string.lower(vendor.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 SetFactionColor()
        if vendor.faction == "alliance" then
            text:SetTextColor(unpack(C.COLORS.ALLIANCE))
        elseif vendor.faction == "horde" then
            text:SetTextColor(unpack(C.COLORS.HORDE))
        else
            text:SetTextColor(unpack(C.COLORS.NEUTRAL))
        end
    end

    SetFactionColor()

    if isFound and vendorSettings.markFoundVendors then
        text:SetTextColor(0.6, 0.6, 0.6)
        text:SetAlpha(0.7)
    end

local function UpdatePreview(vendor)
    if not vendor then
        return
    end

    dv.contentArea._isVendorPreview = true

    -------------------------------------------------
    -- Title
    -------------------------------------------------

    if dv.modelTitle then
        dv.modelTitle:SetText(vendor.title or "Vendor")

        local faction = vendor.faction or "neutral"
        dv.modelTitle:SetTextColor(dv.GetFactionColor(faction))
    end

    -------------------------------------------------
    -- Vendor NPC model
    -- Vendor model3D values are creature display IDs,
    -- so use ShowPreviewCreature, not ShowPreviewModel.
    -------------------------------------------------

    if vendor.model3D then
        dv.ShowPreviewCreature(vendor.model3D, vendor.title or "Vendor")

        local actor = dv.previewActor

        if actor and actor.SetAnimation then
            actor:SetAnimation(0)
        end

        if actor and actor.SetFacing then
            actor:SetFacing(0)
        end

        C_Timer.After(0.05, function()
            local ms = dv.modelScene
            local camera = ms and ms:GetActiveCamera()

            if not camera then
                return
            end

            local cam = dv.VendorCameraOverrides and dv.VendorCameraOverrides[vendor.model3D] or {
                targetZ = 0.4,
                pitch = 0.1,
                zoom = 5.5,
            }

            if camera.SetTarget then
                camera:SetTarget(0, 0, cam.targetZ or 0.4)
            end

            if camera.SetPitch then
                camera:SetPitch(cam.pitch or 0.1)
            end

            if camera.SetZoomDistance then
                camera:SetZoomDistance(cam.zoom or 5.5)
            end
        end)

    else
        if dv.SetPreviewWatermarkVisible then
            dv.SetPreviewWatermarkVisible(true)
        end
    end

    if dv.texture then
        dv.texture:Hide()
    end
end

line:SetScript("OnClick", function(self, button)

    -- 🟢 LEFT CLICK
if button == "LeftButton" then
    UpdatePreview(vendor)
    dv.ShowVendorPopup(vendor.id, vendor.title)

    if not dv.vendorNotes then return end

    if vendor.note and vendor.note ~= "" then
        dv.vendorNotes.text:SetText(vendor.note)

        -- Force width so GetStringHeight calculates wrapping correctly.
        local width = dv.vendorNotes:GetWidth() or 0
        if width > 20 then
            dv.vendorNotes.text:SetWidth(width - 20)
        end

        local textHeight = dv.vendorNotes.text:GetStringHeight() or 0
        dv.vendorNotes:SetHeight(math.max(42, textHeight + 20))
        dv.vendorNotes:Show()
    else
        dv.vendorNotes.text:SetText("")
        dv.vendorNotes:Hide()
    end
end

    -- 🔵 RIGHT CLICK (WAYPOINT)
    if button == "RightButton" then
        if vendor.mapID and vendor.x and vendor.y then

            if hasTomTom and TomTom then
                TomTom:AddWaypoint(
                    vendor.mapID,
                    vendor.x / 100,
                    vendor.y / 100,
                    {
                        title = vendor.title .. " - " .. (vendor.zone or ""),
                        persistent = false,
                        minimap = true,
                        world = true,
                    }
                )
            end

            local vec = CreateVector2D(vendor.x / 100, vendor.y / 100)
            local mapPoint = UiMapPoint.CreateFromVector2D(vendor.mapID, vec)
            C_Map.SetUserWaypoint(mapPoint)
            C_SuperTrack.SetSuperTrackedUserWaypoint(true)
        end
    end

end)

    line:SetScript("OnEnter", function()

        text:SetTextColor(1, 0.82, 0.2)

        GameTooltip:SetOwner(line, "ANCHOR_LEFT")
        GameTooltip:AddLine(vendor.title, 1, 1, 1)

        if vendor.zone then
            GameTooltip:AddLine("Zone: " .. vendor.zone, 0.8, 0.8, 0.8)
        end

        if vendor.mapID then
            local mapInfo = C_Map.GetMapInfo(vendor.mapID)
            if mapInfo then
                GameTooltip:AddLine(mapInfo.name, C.COLORS.GOLD)
            end
        end

        GameTooltip:AddLine(" ")
        GameTooltip:AddLine("|cff00ff00Left Click|r Open Vendor Items")
        GameTooltip:AddLine("|cff00ff00Right Click|r Set Waypoint")

        GameTooltip:Show()
    end)

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

        if isFound and vendorSettings.markFoundVendors then
            text:SetTextColor(0.6, 0.6, 0.6)
            text:SetAlpha(0.7)
        else
            SetFactionColor()
            text:SetAlpha(1)
        end
    end)

    table.insert(dv.activeWidgets, line)

    return y - 22
end
