-- navigation.lua v1.4 (Scrap-O-Matic Edition)
local ADDON_NAME, WDIGI = ...
WDIGI.Navigation = WDIGI.Navigation or {}

------------------------------------------------------------
-- NAV HUD FRAME
------------------------------------------------------------
local navHUD = CreateFrame("Frame", "WDIGINavHUD", UIParent, "BackdropTemplate")
WDIGI.Navigation.HUD = navHUD

navHUD:SetSize(600, 110) 
navHUD:SetPoint("TOP", UIParent, "TOP", 0, -100)
navHUD:Hide()

-- FIX: Layering and Strata
-- DIALOG is above most windows; SetToplevel(true) brings it to the front when clicked
navHUD:SetFrameStrata("DIALOG")
navHUD:SetToplevel(true)

if navHUD.SetBackdrop then
    navHUD:SetBackdrop({
        bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
        edgeFile = "Interface\\Buttons\\WHITE8X8", 
        tile = true, tileSize = 16, edgeSize = 1,
        insets = { left = 0, right = 0, top = 0, bottom = 0 }
    })
    navHUD:SetBackdropColor(0.05, 0.05, 0.05, 1.0) 
    navHUD:SetBackdropBorderColor(0.2, 0.2, 0.2, 1.0) 
end

------------------------------------------------------------
-- LEFT BLOCK (Content Stack)
------------------------------------------------------------
navHUD.leftBlock = CreateFrame("Frame", nil, navHUD)
navHUD.leftBlock:SetPoint("TOPLEFT", 15, -15)
navHUD.leftBlock:SetPoint("BOTTOMRIGHT", navHUD, "BOTTOMRIGHT", -220, 15)

-- 1. Item Icon
navHUD.itemIcon = navHUD.leftBlock:CreateTexture(nil, "OVERLAY")
navHUD.itemIcon:SetSize(52, 52)
navHUD.itemIcon:SetPoint("TOPLEFT", 0, 0)
navHUD.itemIcon:SetTexCoord(0.08, 0.92, 0.08, 0.92) 

-- 2. Vendor Icon
navHUD.vendorIcon = navHUD.leftBlock:CreateTexture(nil, "OVERLAY")
navHUD.vendorIcon:SetSize(18, 18)
navHUD.vendorIcon:SetPoint("TOPLEFT", navHUD.itemIcon, "TOPRIGHT", 12, 0)

-- 3. Header (Teal)
navHUD.title = navHUD.leftBlock:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
navHUD.title:SetPoint("LEFT", navHUD.vendorIcon, "RIGHT", 6, 0)
navHUD.title:SetTextColor(0, 0.8, 1.0) 

-- 4. Vendor Name
navHUD.vendor = navHUD.leftBlock:CreateFontString(nil, "OVERLAY", "GameFontHighlightMedium")
navHUD.vendor:SetPoint("TOPLEFT", navHUD.vendorIcon, "BOTTOMLEFT", 0, -4)
navHUD.vendor:SetPoint("RIGHT", navHUD.leftBlock, "RIGHT", 0, 0)
navHUD.vendor:SetJustifyH("LEFT")
navHUD.vendor:SetMaxLines(1)

-- 5. Item Name (Amber)
navHUD.itemName = navHUD.leftBlock:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
navHUD.itemName:SetPoint("TOPLEFT", navHUD.vendor, "BOTTOMLEFT", 0, -2)
navHUD.itemName:SetPoint("RIGHT", navHUD.leftBlock, "RIGHT", 0, 0)
navHUD.itemName:SetJustifyH("LEFT")
navHUD.itemName:SetTextColor(1, 0.8, 0) 

-- 6. Cost
navHUD.cost = navHUD.leftBlock:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
navHUD.cost:SetPoint("TOPLEFT", navHUD.itemName, "BOTTOMLEFT", 0, -2)
navHUD.cost:SetTextColor(0.6, 0.6, 0.6)

------------------------------------------------------------
-- RIGHT BLOCK (Unified)
------------------------------------------------------------
navHUD.zoneIcon = navHUD:CreateTexture(nil, "OVERLAY")
navHUD.zoneIcon:SetSize(14, 14)
navHUD.zoneIcon:SetTexture("Interface\\AddOns\\Blizzard_SharedMapDataProviders\\Resources\\Map_Quest_Icon")
navHUD.zoneIcon:SetPoint("TOPRIGHT", -15, -15)

navHUD.zoneText = navHUD:CreateFontString(nil, "OVERLAY", "GameFontDisableSmall")
navHUD.zoneText:SetPoint("RIGHT", navHUD.zoneIcon, "LEFT", -4, 0)
navHUD.zoneText:SetTextColor(0, 0.8, 1.0)

navHUD.arrow = navHUD:CreateTexture(nil, "OVERLAY")
navHUD.arrow:SetSize(64, 64)
navHUD.arrow:SetPoint("RIGHT", -15, 0)
navHUD.arrow:SetTexture("Interface\\Minimap\\MiniMap-QuestArrow")
navHUD.arrow:SetVertexColor(0.2, 1, 0.2)

navHUD.dist = navHUD:CreateFontString(nil, "OVERLAY", "GameFontHighlightHuge")
navHUD.dist:SetPoint("RIGHT", navHUD.arrow, "LEFT", -8, 0)
navHUD.dist:SetTextColor(0.2, 1, 0.2)

-- Travel Icon (Anchored to the HUD frame for stability)
navHUD.travelIcon = navHUD:CreateTexture(nil, "OVERLAY", nil, 7)
navHUD.travelIcon:SetSize(28, 28)
navHUD.travelIcon:SetTexture("Interface\\FriendsFrame\\Icon-WoW") 
navHUD.travelIcon:SetPoint("CENTER", navHUD.arrow, "CENTER", 0, 0)
navHUD.travelIcon:SetVertexColor(1, 0.8, 0) 
navHUD.travelIcon:Hide()

------------------------------------------------------------
-- CLOSE BUTTON & DRAG
------------------------------------------------------------
navHUD.close = CreateFrame("Button", nil, navHUD, "UIPanelCloseButton")
navHUD.close:SetPoint("TOPRIGHT", 2, 2)
navHUD.close:SetScale(0.7)
navHUD.close:SetScript("OnClick", function()
    navHUD:Hide()
    C_Map.ClearUserWaypoint()
    if SuperTrackedFrame then SuperTrackedFrame:SetAlpha(1) end
    if SelectionArrow then SelectionArrow:SetAlpha(1) end
end)

navHUD:EnableMouse(true)
navHUD:SetMovable(true)
navHUD:RegisterForDrag("LeftButton")
navHUD:SetScript("OnDragStart", navHUD.StartMoving)
navHUD:SetScript("OnDragStop", navHUD.StopMovingOrSizing)

------------------------------------------------------------
-- LOGIC FUNCTIONS
------------------------------------------------------------
function WDIGI.Navigation.UpdateHUD(x, y, vendorName, itemName, cost, sourceType, targetZoneID, itemIcon, vendorIcon, npcID, sType)
    navHUD.tx = tonumber(x)
    navHUD.ty = tonumber(y)
    navHUD.targetZoneID = tonumber(targetZoneID)
    
    -- SMART LABELING:
    -- 'sType' comes from our normalized data (creature/gameobject)
    -- 'sourceType' is the UI category (Sold by, Dropped by, etc.)
    local label = sourceType or "NAVIGATING TO:"
    
    if sType == "creature" then
        label = "FIND NPC:"
    elseif sType == "gameobject" then
        label = "FIND OBJECT:"
    end
    
    navHUD.title:SetText(label)

    navHUD.sourceType = label

    local cleanVendor = tostring(vendorName or "Unknown Vendor"):gsub("|c%x%x%x%x%x%x%x%x", ""):gsub("|r", "")
    navHUD.vendor:SetText(cleanVendor)
    navHUD.itemName:SetText(itemName or "")
    navHUD.cost:SetText(cost or "")
    
    -- Icon Syncing
    navHUD.itemIcon:SetTexture(itemIcon or 134400)
    
    -- RICH ICONS: Use the portrait if it's an NPC
    if sType == "creature" or (npcID and npcID > 0) then
        navHUD.vendorIcon:SetTexture(135911)
        navHUD.vendorIcon:SetTexCoord(0.15, 0.85, 0.15, 0.85)
    else
        navHUD.vendorIcon:SetTexture(vendorIcon or 134400)
        navHUD.vendorIcon:SetTexCoord(0, 1, 0, 1)
    end
    
    navHUD:Show()
end

------------------------------------------------------------
-- SET MAP-PIN USING OUR NAV OR TOMTOM
------------------------------------------------------------
function WDIGI.Navigation.SetPin(mapID, x, y, vendorName, itemName, cost, sourceType, itemIcon, vendorIcon, npcID, sType)
    local mID = tonumber(mapID)
    local nX, nY = tonumber(x), tonumber(y)
    
    if not mID or not nX or not nY or mID == 0 then return end

    -- 1. CALCULATE NORMALIZED VALUES
    -- Export stores coords as 2240 (for 22.40)
    local floatX, floatY = nX / 10000, nY / 10000 -- e.g., 0.2240
    local tomX, tomY = nX / 100, nY / 100       -- e.g., 22.40

    local useHUD = WDIGI.Settings.Get("WDIGI_EnableNavHUD_Experimental")
    
    if useHUD and WDIGI.Navigation.StartHUD then
        -- Start your HUD logic
        WDIGI.Navigation.StartHUD(mID, nX, nY, vendorName)
        
        -- Set the Retail Blizzard Waypoint (0.0 - 1.0)
        local point = UiMapPoint.CreateFromCoordinates(mID, floatX, floatY)
        C_Map.SetUserWaypoint(point)
        C_SuperTrack.SetUserWaypointTracked(true)
    elseif TomTom and TomTom.AddWaypoint then
        -- Pass the 0-100 values to TomTom
        TomTom:AddWaypoint(mID, tomX, tomY, {
            title = vendorName or "Destination",
            arrivaldistance = 15,
            cleardistance = 10,
        })
    end

    -- Clean up Blizzard UI clutter
    if SuperTrackedFrame then SuperTrackedFrame:SetAlpha(0) end
    if SelectionArrow then SelectionArrow:SetAlpha(0) end

    -- Update HUD with rich metadata
    WDIGI.Navigation.UpdateHUD(nX, nY, vendorName, itemName, cost, sourceType, mID, itemIcon, vendorIcon, npcID, sType)
end

------------------------------------------------------------
-- ONUPDATE ENGINE
------------------------------------------------------------
navHUD:SetScript("OnUpdate", function(self, elapsed)
    local arrowEnabled = WDIGI.Settings.Get("WDIGI_EnableNavHUD_Experimental")
    
    -- Visual Ghost Kill
    if SuperTrackedFrame then SuperTrackedFrame:SetAlpha(0) end
    if SelectionArrow then SelectionArrow:SetAlpha(0) end

    self.timer = (self.timer or 0) + elapsed
    if self.timer < 0.1 then return end
    self.timer = 0

    local targetID = self.targetZoneID
    if not targetID or targetID == 0 then return end

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

    -- Zone Name Update
    local mapInfo = C_Map.GetMapInfo(targetID)
    self.zoneText:SetText((mapInfo and mapInfo.name or "Unknown"):upper())

    -- Cross-Zone State
    if currentMap ~= targetID then
        self.dist:SetText("TRAVELING")
        self.dist:SetTextColor(1, 0.8, 0)
        self.zoneText:SetTextColor(1, 0.8, 0)
        self.travelIcon:Show()
        self.arrow:Hide()
        return
    else
        self.zoneText:SetTextColor(0, 0.8, 1.0)
        self.travelIcon:Hide()
    end

    -- Math & Position
    local pos = C_Map.GetPlayerMapPosition(currentMap, "player")
    if not pos then return end

    local dx, dy = (self.tx / 100) - pos.x, pos.y - (self.ty / 100)
    local angle = math.atan2(dx, dy) 
    local rel = angle - (GetPlayerFacing() or 0)

    local yards = math.floor(math.sqrt(dx*dx + dy*dy) * (WDIGI.MapUtils.GetZoneMultiplier(currentMap) or 1000))

    -- HUD Updates
    navHUD.title:SetText(WDIGI.Settings.DebugNav() and string.format("REL: %.1f°", math.deg(rel)) or self.sourceType)

    if arrowEnabled then
        self.arrow:SetRotation(rel - (math.pi / 2)) 
        self.arrow:Show()
    else
        self.arrow:Hide()
    end

    if yards <= 3 then
        self:Hide()
        C_Map.ClearUserWaypoint()
        if SuperTrackedFrame then SuperTrackedFrame:SetAlpha(1) end
        UIErrorsFrame:AddMessage("Arrived at Destination!", 0, 1, 0)
        return
    end

    self.dist:SetText(yards .. "yd")
    self.dist:SetTextColor(0.2, 1, 0.2)
end)