Custom window issue

I'm trying to make this custom window appear and disappear after a short period, it mostly works and the window/text does, but the picture stays on the screen, even trying with screen.pictures show/erase didn't work.


Ruby:
class CustomWindow < Window_Base
  def initialize(x, y, width, height, text, duration)
    super(x, y, width, height)
    @text = text
    @duration = duration
    @timer = 0
    draw_text
  end

  def draw_text
    contents.clear
    contents.draw_text(0, 0, width - 32, line_height, @text, 1)
  end

  def update
    super
    @timer += 1
    dispose if @timer >= @duration
  end
end

def show_custom_window(x, y, width, height, text, duration)
  $text_window = CustomWindow.new(x, y + height, width, 100, text, duration)
  $text_window.opacity = 255
  $text_window.z = 9999
 
  $picture_sprite = Sprite.new
  $picture_sprite.bitmap = Cache.picture("Badge")
  $picture_sprite.x = x
  $picture_sprite.y = y
  $picture_sprite.opacity = 255
  $picture_sprite.z = 9999

  #screen.pictures[2].show("Badge", 0, 0, 0, 100, 100, 255, 0)

  $start_time = Graphics.frame_count
  $duration_frames = duration
end


class Scene_Map < Scene_Base
  alias custom_update update
 
  def update
    custom_update
    if $text_window && !$text_window.disposed?
      $text_window.update
      if Graphics.frame_count - $start_time >= $duration_frames
        $picture_sprite.dispose
        $picture_sprite = nil
        #screen.pictures[2].erase
        $text_window.dispose
        $text_window = nil
      end
    end
  end
 
  alias custom_terminate terminate
  def terminate
    custom_terminate
    if Graphics.frame_count - $start_time >= $duration_frames
        $picture_sprite.dispose
        $picture_sprite = nil
        #screen.pictures[2].erase
        $text_window.dispose
        $text_window = nil
      end
  end

end

Original thread: https://forums.rpgmakerweb.com/threads/custom-window-issue.171682/