local DGV = DugisGuideViewer
local DGU
if not DGV then return end

------------ 
-- Config --
------------

local objectiveIconSize = 1
local objectiveIconYPosition = -13
local lootIconSize = 1.2
local lootIconDistance = 7
local itemIconSize = 1
local itemIconDistance = 5
local objectveTextXPosition = 0
local maxTextWidth = 275

local NamePlate, L = DGV:RegisterModule("NamePlate"), DugisLocals
DGV.NamePlate = NamePlate

local ActivePlates = {}
local PlateId2CostomizedFrames = {}
local DugiQuestPlateTooltip = CreateFrame('GameTooltip', 'DugiQuestPlateTooltip', nil, 'GameTooltipTemplate')

---------------------------------------------------------
-- SAFE FONT HELPERS (Classic Anniversary Compatible)
---------------------------------------------------------

local function SafeSetFont(fs, size)
    -- Classic Anniversary does NOT ship GameFontHighlightSmall
    -- Use FRIZQT__.TTF which is guaranteed to exist
    fs:SetFont("Fonts\\FRIZQT__.TTF", size or 12, "")
end

local function EnsurePlateObjects(plateFrame)
    if plateFrame.DugiIcon then return end

    plateFrame.DugiIcon = CreateFrame("Frame", nil, plateFrame)
    plateFrame.DugiIcon:SetFrameLevel(10)
    plateFrame.DugiIcon:Show()

    plateFrame.DugiIcon.Texture = plateFrame.DugiIcon:CreateTexture(nil, "OVERLAY")
    plateFrame.DugiIcon.Texture:SetAllPoints()

    -- Loot icon
    local DugiIconLoot = CreateFrame("Frame", nil, plateFrame)
    DugiIconLoot:SetFrameLevel(11)
    DugiIconLoot:Show()
    DugiIconLoot.Texture = DugiIconLoot:CreateTexture(nil, "OVERLAY")
    DugiIconLoot.Texture:SetAllPoints()
    plateFrame.DugiIcon.DugiIconLoot = DugiIconLoot

    -- Item icon
    local DugiIconItem = CreateFrame("Frame", nil, plateFrame)
    DugiIconItem:SetFrameLevel(12)
    DugiIconItem:Show()
    DugiIconItem.Texture = DugiIconItem:CreateTexture(nil, "OVERLAY")
    DugiIconItem.Texture:SetAllPoints()
    plateFrame.DugiIcon.DugiIconItem = DugiIconItem

    -- Objective text
    local ObjectiveText = plateFrame:CreateFontString(nil, "OVERLAY")
    SafeSetFont(ObjectiveText, 12)
    ObjectiveText:SetJustifyH("LEFT")
    ObjectiveText:SetWidth(maxTextWidth)
    ObjectiveText:SetWordWrap(false)
    ObjectiveText:SetText("")
    ObjectiveText:Show()
    plateFrame.DugiIcon.ObjectiveText = ObjectiveText

    -- Counter text
    local CounterText = plateFrame.DugiIcon:CreateFontString(nil, "OVERLAY")
    SafeSetFont(CounterText, 12)
    CounterText:SetPoint("CENTER", plateFrame.DugiIcon, 0.8, 0)
    CounterText:SetShadowOffset(1, -1)
    CounterText:SetTextColor(1, .82, 0)
    CounterText:Show()
    plateFrame.DugiIcon.CounterText = CounterText
end

---------------------------------------------------------
-- MAIN NAMEPLATE UPDATE LOGIC
---------------------------------------------------------

function NamePlate:OnNAME_PLATE_UNIT_ADDED(_, plateID)
    ActivePlates[plateID] = {
        frame = C_NamePlate.GetNamePlateForUnit(plateID),
        unitName = UnitName(plateID),
        unitGUID = UnitGUID(plateID),
        plateID = plateID
    }

    if self.UpdateActivePlatesExtras then
        self:UpdateActivePlatesExtras(plateID)
    end
end

NamePlate.ShouldLoad = function()
    return true
end

function NamePlate:Initialize()
    DGU = DugisGuideUser
    DGV.NamePlate = NamePlate

    function self:SetDugiNameplate(plateFrame, showIcon, text, iconSize, itemsCount, lootIcon, itemTexture_, objectIcon)
        EnsurePlateObjects(plateFrame)

        local DugiIcon = plateFrame.DugiIcon
        local ObjectiveText = DugiIcon.ObjectiveText
        local CounterText = DugiIcon.CounterText

        if showIcon then
            DugiIcon:SetSize(30 * objectiveIconSize * iconSize, 30 * objectiveIconSize * iconSize)

            local iconSizeForLootAndItem = iconSize > 1.4 and 1.4 or iconSize

            DugiIcon.DugiIconLoot:SetSize(15 * lootIconSize * iconSizeForLootAndItem, 15 * lootIconSize * iconSizeForLootAndItem)
            DugiIcon.DugiIconItem:SetSize(15 * itemIconSize * iconSizeForLootAndItem, 15 * itemIconSize * iconSizeForLootAndItem)

            local lootIconFinalDistance = 9 + itemIconDistance + iconSize * 8 - 8
            DugiIcon.DugiIconLoot:SetPoint("TOPLEFT", DugiIcon, "BOTTOMRIGHT", -lootIconFinalDistance, lootIconFinalDistance)

            local itemIconFinalDistance = 5 + itemIconDistance + iconSize * 8 - 8
            DugiIcon.DugiIconItem:SetPoint("TOPRIGHT", DugiIcon, "BOTTOMLEFT", itemIconFinalDistance, itemIconFinalDistance)

            ObjectiveText:Hide()

            if text and text ~= "" then
                local textSize = ((DugisGuideViewer:GetDB(DGV_NAMEPLATETEXTSIZE) or 5) / 10) * 12 + 10
                SafeSetFont(ObjectiveText, textSize)

                ObjectiveText:SetText(text)
                ObjectiveText:Show()

                local TextW = ObjectiveText:GetStringWidth()
                if TextW > maxTextWidth then TextW = maxTextWidth end

                local spaceX = 2
                local iconWidth = DugiIcon:GetWidth()
                local totalWidth = iconWidth + spaceX + TextW
                local iconX

                DugiIcon:ClearAllPoints()
                ObjectiveText:ClearAllPoints()

                if DugisGuideViewer:GetDB(DGV_NAMEPLATES_SHOW_TEXT) then
                    iconX = -(totalWidth * 0.5) + plateFrame:GetWidth() * 0.5
                else
                    iconX = plateFrame:GetWidth() * 0.5 - iconWidth * 0.5
                end

                if DugisGuideViewer:GetDB(DGV_NAMEPLATES_SHOW_ICON) then
                    ObjectiveText:SetPoint("LEFT", DugiIcon, "RIGHT", spaceX, 0)
                    ObjectiveText:SetJustifyH("LEFT")
                else
                    ObjectiveText:SetPoint("BOTTOM", plateFrame, "TOP", 0, 10)
                    ObjectiveText:SetJustifyH("CENTER")
                end

                DugiIcon:SetPoint("BOTTOMLEFT", plateFrame, "TOPLEFT", iconX, 15 + objectiveIconYPosition)
            else
                DugiIcon:ClearAllPoints()
                DugiIcon:SetPoint("BOTTOM", plateFrame, "TOP", 0, 15 + objectiveIconYPosition)
            end

            if itemsCount and itemsCount > 0 then
                CounterText:SetText(tostring(itemsCount))
                local iconTextSize = iconSize * 12
                if itemsCount > 9 then iconTextSize = iconTextSize * 0.8 end
                SafeSetFont(CounterText, iconTextSize)
                CounterText:Show()
            else
                CounterText:Hide()
            end

            DugiIcon:Hide()
            if showIcon then
                if CounterText:IsShown() then
                    DugiIcon.Texture:SetTexture("Interface/QuestFrame/AutoQuest-Parts")
                    DugiIcon.Texture:SetTexCoord(0.30273438, 0.41992188, 0.015625, 0.953125)
                else
                    DugiIcon.Texture:SetTexture("Interface/AddOns/DugisGuideViewerZ/Artwork/accept.tga")
                    DugiIcon.Texture:SetTexCoord(0,1,0,1)
                end
                DugiIcon:Show()
            end

            DugiIcon.DugiIconLoot:Hide()
            if lootIcon then
                DugiIcon.DugiIconLoot.Texture:SetTexture("Interface\\Minimap\\TRACKING\\Banker")
                DugiIcon.DugiIconLoot:Show()
            end

            if objectIcon then
                DugiIcon.DugiIconLoot.Texture:SetTexture("Interface\\AddOns\\DugisGuideViewerZ\\Artwork\\cog_kill.tga")
                DugiIcon.DugiIconLoot:Show()
            end

            DugiIcon.DugiIconItem:Hide()
            if itemTexture_ then
                DugiIcon.DugiIconItem.Texture:SetTexture(itemTexture_)
                DugiIcon.DugiIconItem.Texture:Show()
                DugiIcon.DugiIconItem:Show()
            end

            if not DugisGuideViewer:GetDB(DGV_NAMEPLATES_SHOW_ICON) then
                DugiIcon:Hide()
                DugiIcon.DugiIconItem:Hide()
                DugiIcon.DugiIconLoot:Hide()
            end

            if not DugisGuideViewer:GetDB(DGV_NAMEPLATES_SHOW_TEXT) then
                ObjectiveText:Hide()
            end
        else
            CounterText:Hide()
            ObjectiveText:Hide()
            DugiIcon:Hide()
            DugiIcon.DugiIconItem:Hide()
            DugiIcon.DugiIconLoot:Hide()
        end
    end

    ---------------------------------------------------------
    -- The rest of your file remains unchanged
    ---------------------------------------------------------

    function self:CurrentSmallFrameStepsInfo()
        local npcId2firstQuestInfo = {}

        if not DGV.quests1L then
            return npcId2firstQuestInfo
        end

        for questIndex in DGV.IterateRelevantSteps do
            local questTitle = DGV.quests1L[questIndex]
            if not questTitle then return npcId2firstQuestInfo end

            local completed = (DGV:GetQuestState(questIndex) == "C")
            if not completed then
                local npcId = tonumber(DGV:ReturnTag("NPC", questIndex))
                if npcId and not npcId2firstQuestInfo[npcId] then
                    npcId2firstQuestInfo[npcId] = { questName = questTitle }
                end
            end
        end

        return npcId2firstQuestInfo
    end

    function self:OnNAME_PLATE_UNIT_REMOVED(_, plateID)
        ActivePlates[plateID] = nil
    end

    local QuestLogIndex = {}
    function CacheQuestIndexes()
        wipe(QuestLogIndex)
        for i = 1, GetNumQuestLogEntries() do
            local title, _, _, isHeader = GetQuestLogTitle(i)
            if not isHeader then QuestLogIndex[title] = i end
        end
        self:UpdateActivePlatesExtras()
    end

    local function GetQuestProgress(unitID)
        DugiQuestPlateTooltip:SetOwner(UIParent, 'ANCHOR_NONE')
        DugiQuestPlateTooltip:SetUnit(unitID)
        DugiQuestPlateTooltip:Show()

        local targetName = DugiQuestPlateTooltipTextLeft1:GetText()
        local questInfo = DGV.GetQuestInfoByTargetName(targetName)

        if #questInfo.objectives > 0 then
            return questInfo.objectives[1],
                   questInfo.objectives[1].leftAmount,
                   questInfo.objectives[1].questInfo.index,
                   questInfo.objectives[1].questInfo.questId,
                   questInfo.objectives[1].questInfo,
                   questInfo
        end
    end

    function self:NamePlateInfo2VisualizationData(info)
        if not DugisGuideViewer:GetDB(DGV_NAMEPLATES_TRACKING)
        or ((not DugisGuideViewer:GetDB(DGV_NAMEPLATES_SHOW_ICON)) and
            (not DugisGuideViewer:GetDB(DGV_NAMEPLATES_SHOW_TEXT))) then
            return false
        end

        local showIcon = false
        local text = nil
        local iconSize = ((DugisGuideViewer:GetDB(DGV_NAMEPLATEICONSIZE) or 5) / 10) * 1.5 + 0.5

        local lootIcon = false
        local objectIcon = false
        local itemTexture_ = nil

        local namePlateUnitId = DGV:GuidToNpcId(info.unitGUID)
        local dropNames = DGV:GetUnitDropNames(tonumber(namePlateUnitId))

        local _, objectiveCount, _, _, _, questInfo_ = GetQuestProgress(info.plateID)
        local leftItems = objectiveCount

        if questInfo_ and #questInfo_.objectives > 0 then
            showIcon = true
            local lastText = ""

            for _, objective in pairs(questInfo_.objectives) do
                lastText = objective.text
                leftItems = objective.leftAmount

                if objective.type == "item" then lootIcon = true end
                if objective.type == "npc" then objectIcon = true end

                if dropNames[objective.item_NPC_name] then
                    objectIcon = true
                    text = objective.text
                end

                if objective.itemId then
                    itemTexture_ = select(10, GetItemInfo(tonumber(objective.itemId)))
                end
            end

            if not text then text = lastText end
        else
            local npcId2firstQuestInfo = self:CurrentSmallFrameStepsInfo()
            namePlateUnitId = tonumber(namePlateUnitId)

            if namePlateUnitId then
                local firstQuestInfo = npcId2firstQuestInfo[namePlateUnitId]
                if firstQuestInfo then
                    showIcon = true
                    text = firstQuestInfo.questName
                    leftItems = leftItems or 0
                    lootIcon = false
                    itemTexture_ = nil
                    objectIcon = false
                end
            end
        end

        return showIcon, text, iconSize, leftItems, lootIcon, itemTexture_, objectIcon
    end

    function self:UpdateActivePlatesExtras(plateID)
        for _, info in pairs(ActivePlates) do
            if plateID == nil or plateID == info.plateID then
                NamePlate:SetDugiNameplate(info.frame, self:NamePlateInfo2VisualizationData(info))
            end
        end
    end

    function self:QUEST_LOG_UPDATE()
        CacheQuestIndexes()
    end

    function self:UNIT_QUEST_LOG_CHANGED(unitID)
        if unitID == 'player' then CacheQuestIndexes() end
    end

    local lastAmountOfWatched = nil
    function self:QuestWatch_Update()
        if GetNumQuestWatches() ~= lastAmountOfWatched then
            NamePlate:UpdateActivePlatesExtras()
            lastAmountOfWatched = GetNumQuestWatches()
        end
    end

    function self:Load() end
    function self:Unload()
        NamePlate:UpdateActivePlatesExtras()
    end
end
