-- navigation.lua (Final Version — Auto Map Rotation + Debug Toggle)
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(360, 110)
navHUD:SetPoint("TOP", UIParent, "TOP", 0, -100)
navHUD:Hide()

if navHUD.SetBackdrop then
    navHUD:SetBackdrop({
        bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
        edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
        tile = true, tileSize = 16, edgeSize = 16,
        insets = { left = 4, right = 4, top = 4, bottom = 4 }
    })
    navHUD:SetBackdropColor(0, 0, 0, 0.9)
end

------------------------------------------------------------
-- LEFT BLOCK (Tooltip-style vertical stack)
------------------------------------------------------------
navHUD.leftBlock = CreateFrame("Frame", nil, navHUD)
navHUD.leftBlock:SetPoint("LEFT", 12, 0)
navHUD.leftBlock:SetSize(220, 80) -- auto-adjust later if needed

-- 1. Item Icon
navHUD.itemIcon = navHUD.leftBlock:CreateTexture(nil, "OVERLAY")
navHUD.itemIcon:SetSize(42, 42)
navHUD.itemIcon:SetPoint("TOPLEFT", 0, -2)

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

-- 3. Header Text (same row as vendor icon)
navHUD.title = navHUD.leftBlock:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
navHUD.title:SetPoint("LEFT", navHUD.vendorIcon, "RIGHT", 4, 0)
navHUD.title:SetTextColor(0.7, 0.7, 0.7)

-- 4. Vendor Name (under vendor icon)
navHUD.vendor = navHUD.leftBlock:CreateFontString(nil, "OVERLAY", "GameFontHighlightMedium")
navHUD.vendor:SetPoint("TOPLEFT", navHUD.vendorIcon, "BOTTOMLEFT", 0, -1)
navHUD.vendor:SetWidth(180)

-- 5. Item Name
navHUD.itemName = navHUD.leftBlock:CreateFontString(nil, "OVERLAY", "GameFontNormal")
navHUD.itemName:SetPoint("TOPLEFT", navHUD.vendor, "BOTTOMLEFT", 0, -1)
navHUD.itemName:SetWidth(180)
navHUD.itemName:SetTextColor(1, 0.82, 0)

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


------------------------------------------------------------
-- ARROW & DISTANCE (Right Aligned)
------------------------------------------------------------
navHUD.arrow = navHUD:CreateTexture(nil, "OVERLAY")
navHUD.arrow:SetSize(64, 64)
navHUD.arrow:SetPoint("RIGHT", -12, 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", -4, 0)

------------------------------------------------------------
-- CLOSE BUTTON & DRAG LOGIC
------------------------------------------------------------
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()
end)

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

------------------------------------------------------------
-- UPDATE HUD
------------------------------------------------------------
function WDIGI.Navigation.UpdateHUD(x, y, vendorName, itemName, cost, sourceType, targetZoneID, itemIcon, vendorIcon)
    navHUD.tx = tonumber(x)
    navHUD.ty = tonumber(y)
    navHUD.targetZoneID = tonumber(targetZoneID)
    navHUD.lastDist = nil
    navHUD.sourceType = sourceType or "NAVIGATING TO:"

    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 "")

    navHUD.itemIcon:SetTexture(itemIcon or "Interface\\Icons\\INV_Misc_QuestionMark")
    navHUD.vendorIcon:SetTexture(vendorIcon or "Interface\\Icons\\INV_Misc_QuestionMark")

    navHUD:Show()
end

------------------------------------------------------------
-- SET PIN (REAL MAP LOGIC)
------------------------------------------------------------
function WDIGI.Navigation.SetPin(mapID, x, y, vendorName, itemName, cost, sourceType, itemIcon, vendorIcon)
    local mID = tonumber(mapID)
    local nX  = tonumber(x)
    local nY  = tonumber(y)

    if not mID or not nX or not nY or mID == 0 then return end

    local dx, dy = nX / 100, nY / 100
    if dx < 0 or dx > 1 or dy < 0 or dy > 1 then return end

    local point = UiMapPoint.CreateFromCoordinates(mID, dx, dy)
    C_Map.SetUserWaypoint(point)

    if C_SuperTrack and C_SuperTrack.SetSuperTrackedUserWaypoint then
        C_SuperTrack.SetSuperTrackedUserWaypoint(true)
    end

    WDIGI.Navigation.UpdateHUD(nX, nY, vendorName, itemName, cost, sourceType, mID, itemIcon, vendorIcon)
end

------------------------------------------------------------
-- ONUPDATE ENGINE
------------------------------------------------------------
navHUD:SetScript("OnUpdate", function(self, elapsed)
    local arrowEnabled = WDIGI.Settings.Get("WDIGI_EnableNavHUD_Experimental")

    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

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

    local px, py = pos.x, pos.y

    -- Distance Calculation
    if currentMap ~= targetID then
        local mapInfo = C_Map.GetMapInfo(targetID)
        self.dist:SetText(mapInfo and mapInfo.name or "Wrong Zone")
        self.dist:SetTextColor(0.6, 0.6, 0.6)
        self.arrow:Hide()
        return
    end

    local tx, ty = self.tx / 100, self.ty / 100
    local mdx, mdy = tx - px, ty - py
    local rawDist = math.sqrt(mdx * mdx + mdy * mdy)
    local mult = WDIGI.MapUtils.GetZoneMultiplier(currentMap) or 1000
    local yards = math.floor(rawDist * mult)

    -- Arrow Rotation
    local info = C_Map.GetMapInfo(currentMap)
    local cosr = info and info.horizontalCos or 1
    local sinr = info and info.horizontalSin or 0

    local wx = mdx * cosr - mdy * sinr
    local wy = mdx * sinr + mdy * cosr

    local angle = math.atan2(wy, wx)
    local facing = GetPlayerFacing() or 0
    local rel = angle - facing

    if WDIGI.Settings.DebugNav() then
        navHUD.title:SetText(string.format("REL: %.1f°", math.deg(rel)))
    else
        navHUD.title:SetText(self.sourceType or "NAVIGATING TO:")
    end

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

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

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