local ADDON_NAME, ns = ...

local function MN_ApplyOverlay()
  if not (WorldMapFrame and WorldMapFrame.ScrollContainer and WorldMapFrame.ScrollContainer.Child) then return end

  local child = WorldMapFrame.ScrollContainer.Child
  local children = { child:GetChildren() }

  for _, pin in ipairs(children) do
    if pin and pin.GetObjectType and (pin:GetObjectType() == "Button" or pin:GetObjectType() == "Frame") then
      local onEnter = pin.GetScript and pin:GetScript("OnEnter")

      local isMapNotes = (pin.pluginName == "MapNotes") or (ns.pluginHandler and (pin.handler == ns.pluginHandler or pin.pluginHandler == ns.pluginHandler or onEnter == ns.pluginHandler.OnEnter))
      if isMapNotes then
        if pin.SetFrameStrata then pin:SetFrameStrata("DIALOG") end
        if pin.SetFrameLevel then pin:SetFrameLevel(2000) end
      end
    end
  end
end

local function MN_ScheduleOverlay()
  C_Timer.After(0, MN_ApplyOverlay)
  C_Timer.After(0.05, MN_ApplyOverlay)
end

C_Timer.After(0, function()
  if not WorldMapFrame then return end

  WorldMapFrame:HookScript("OnShow", MN_ScheduleOverlay)

  if type(WorldMapFrame.OnMapChanged) == "function" then
    hooksecurefunc(WorldMapFrame, "OnMapChanged", MN_ScheduleOverlay)
  else
    hooksecurefunc(WorldMapFrame, "SetMapID", MN_ScheduleOverlay)
  end

  if ns.Addon and ns.Addon.RegisterMessage then
    ns.Addon:RegisterMessage("HandyNotes_NotifyUpdate", function(_, plugin)
      if plugin == "MapNotes" then
        MN_ScheduleOverlay()
      end
    end)
  end
end)