Imports System.Xml.Serialization

<Serializable>
Public Class MapTile

    <XmlIgnore>
    Public Property Image As Image

    Public Property AnimationFrames As List(Of Image) = Nothing
    Public Property IsAnimated As Boolean = False
    Public Property AnimationInterval As Integer = 200

    Private currentAnimationFrameIndex As Integer = 0

    Private lastAnimationUpdateTime As Date = Date.Now

    Public Property ImageFilePath As String
    Public Property Position As Point
    Public Property Size As Size
    Public Property OriginalSize As Size

    Public Property RotationAngle As Integer = 0

    Public Property IsFlippedHorizontally As Boolean = False

    Public Property IsFlippedVertically As Boolean = False

    Public Property IsLocked As Boolean = False

    Public Property IsWalkable As Boolean = False

    <XmlIgnore>
    Public Property Selected As Boolean = False

    <XmlIgnore>
    Public Property InitialPosition As Point

    <XmlIgnore>
    Public Property IsResizing As Boolean = False

    <XmlIgnore>
    Public Property CurrentResizeDirection As ResizeDirections = ResizeDirections.None
    Public Property IsGrouped As Boolean = False
    Public Property OriginalTiles As List(Of MapTile) = New List(Of MapTile)

    <Flags>
    Public Enum ResizeDirections
        None = 0
        Left = 1
        Right = 2
        Top = 4
        Bottom = 8
    End Enum

    Public Property FrameWidth As Integer

    Public Property FrameHeight As Integer

    Public Function Clone() As MapTile
        Dim clonedTile As New MapTile With {
            .ImageFilePath = ImageFilePath,
            .Position = Position,
            .Size = Size,
            .OriginalSize = OriginalSize,
            .Selected = Selected,
            .IsAnimated = IsAnimated,
            .AnimationInterval = AnimationInterval,
            .RotationAngle = RotationAngle,
            .IsFlippedHorizontally = IsFlippedHorizontally,
            .IsFlippedVertically = IsFlippedVertically,
            .IsLocked = IsLocked,
            .FrameWidth = FrameWidth,
            .FrameHeight = FrameHeight
        }

        If IsAnimated AndAlso AnimationFrames IsNot Nothing Then
            clonedTile.AnimationFrames = New List(Of Image)
            For Each img In AnimationFrames
                clonedTile.AnimationFrames.Add(CType(img.Clone(), Image))
            Next
        ElseIf Image IsNot Nothing Then
            clonedTile.Image = CType(Image.Clone(), Image)
        End If

        Return clonedTile
    End Function

    Public Sub Dispose()
        If IsAnimated AndAlso AnimationFrames IsNot Nothing Then
            For Each img In AnimationFrames
                img.Dispose()
            Next
            AnimationFrames.Clear()
            AnimationFrames = Nothing
        ElseIf Image IsNot Nothing Then
            Image.Dispose()
            Image = Nothing
        End If
    End Sub

    Public Function GetCurrentFrame() As Image
        If IsAnimated AndAlso AnimationFrames IsNot Nothing AndAlso AnimationFrames.Count > 0 Then
            Dim currentTime As Date = Date.Now
            If (currentTime - lastAnimationUpdateTime).TotalMilliseconds >= AnimationInterval Then
                currentAnimationFrameIndex = (currentAnimationFrameIndex + 1) Mod AnimationFrames.Count
                lastAnimationUpdateTime = currentTime
            End If
            Return AnimationFrames(currentAnimationFrameIndex)
        ElseIf Image IsNot Nothing Then
            Return Image
        Else
            ' Return a default image or handle the null case
            Return Nothing
        End If
    End Function
End Class

Public Class MapTileData
    Public Property ImageFilePath As String
    Public Property Position As Point
    Public Property Size As Size
    Public Property OriginalSize As Size
    Public Property IsAnimated As Boolean
    Public Property AnimationInterval As Integer
    Public Property RotationAngle As Integer
    Public Property IsFlippedHorizontally As Boolean
    Public Property IsFlippedVertically As Boolean
    Public Property IsLocked As Boolean
    Public Property FrameWidth As Integer
    Public Property FrameHeight As Integer
    Public Property ImageData As String
    Public Property IsWalkable As Boolean ' Add this line
    Public Property IsGrouped As Boolean
    Public Property OriginalTiles As List(Of MapTileData)
    Public Property AnimationFramesData As List(Of String)
End Class

<Serializable>
Public Class CanvasData
    Public Property MapTiles As List(Of MapTileData)
    Public Property GridSize As Integer
    Public Property MapSize As Size
End Class

Imports System.Collections.Concurrent
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Threading
Imports System.Xml.Serialization

Public Class FrmWorld
    Private dragBoxFromMouseDown As Rectangle
    Private currentFileName As String = ""
    Private isModified As Boolean = False
    Private recentSearches As New List(Of String)()
    Private Const MaxSearches As Integer = 10
    Private isUpdatingComboBox As Boolean = False
    Private searchCancellationTokenSource As CancellationTokenSource
    Private Const MaxImagesToDisplay As Integer = 500
    Private ReadOnly imageExtensions() As String = {".jpg", ".jpeg", ".png", ".bmp", ".gif"}
    Private undoStack As New Stack(Of MapAction)
    Private redoStack As New Stack(Of MapAction)
    Private MapPath As String = Path.GetFullPath(Path.Combine(GetProjectDirectory(), "Maps"))

#Region " Initiate "

    Private Sub FrmWorld_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        PopulateTreeView(Path.GetFullPath(Path.Combine(GetProjectDirectory(), "Decor")))
        PicCanvas.AllowDrop = True

        AddHandler CboDimensions.SelectedIndexChanged, AddressOf CboDimensions_SelectedIndexChanged

        CboDimensions.SelectedItem = "32 x 32"

        Dim defaultMapSize As String = "15000 x 10000"

        If Not CboMapSize.Items.Contains(defaultMapSize) Then
            Dim unused = CboMapSize.Items.Add(defaultMapSize)
        End If

        CboMapSize.SelectedItem = defaultMapSize

        AddHandler PicCanvas.CanvasModified, AddressOf CanvasModified_Handler
        AddHandler cboSearch.KeyDown, AddressOf CboSearch_KeyDown
        AddHandler cboSearch.SelectedIndexChanged, AddressOf CboSearch_SelectedIndexChanged
        AddHandler PicCanvas.TileSelected, AddressOf PicCanvas_TileSelected
        AddHandler PicCanvas.TileSizeChanged, AddressOf PicCanvas_TileSizeChanged

        LoadTreeViewState()
        LoadRecentSearches()
    End Sub
    Private Sub LoadRecentSearches()
        Dim searchesFile As String = "RecentSearches.xml"
        If File.Exists(searchesFile) Then
            Dim serializer As New XmlSerializer(GetType(List(Of String)))
            Using reader As New StreamReader(searchesFile)
                recentSearches = CType(serializer.Deserialize(reader), List(Of String))
            End Using
            cboSearch.Items.Clear()
            For Each searchTerm As String In recentSearches
                Dim unused = cboSearch.Items.Add(searchTerm)
            Next
        End If
    End Sub

    Private Sub LoadTreeViewState()
        If File.Exists("TreeViewState.xml") Then
            Dim serializer As New XmlSerializer(GetType(TreeViewState))
            Using reader As New StreamReader("TreeViewState.xml")
                Dim state As TreeViewState = CType(serializer.Deserialize(reader), TreeViewState)

                For Each nodePath As String In state.ExpandedNodes
                    Dim node As TreeNode = FindNodeByPath(TrvFiles.Nodes, nodePath)
                    node?.Expand()
                Next

                If Not String.IsNullOrEmpty(state.SelectedNodePath) Then
                    Dim selectedNode As TreeNode = FindNodeByPath(TrvFiles.Nodes, state.SelectedNodePath)
                    If selectedNode IsNot Nothing Then
                        TrvFiles.SelectedNode = selectedNode
                        selectedNode.EnsureVisible()
                    End If
                End If
            End Using
        End If
    End Sub

    Private Function FindNodeByPath(nodes As TreeNodeCollection, path As String) As TreeNode
        Dim parts() As String = path.Split("\"c)
        Return FindNodeByPathRecursive(nodes, parts, 0)
    End Function

    Private Function FindNodeByPathRecursive(nodes As TreeNodeCollection, parts() As String, index As Integer) As TreeNode
        For Each node As TreeNode In nodes
            If node.Text = parts(index) Then
                Return If(index = parts.Length - 1, node, FindNodeByPathRecursive(node.Nodes, parts, index + 1))
            End If
        Next
        Return Nothing
    End Function

#End Region

#Region " Populate TreeView and FlowPanel "

    Private Async Function LoadImagesAsync(directoryInfo As DirectoryInfo) As Task
        Try
            FLPImages.Controls.Clear()

            Dim imageExtensions() As String = {".jpg", ".jpeg", ".png", ".bmp", ".gif"}
            Dim imageFiles As New List(Of FileInfo)()

            For Each extension As String In imageExtensions
                imageFiles.AddRange(directoryInfo.GetFiles($"*{extension}", SearchOption.TopDirectoryOnly))
            Next

            Dim isInBossesFolder As Boolean = IsInBossesDirectory(directoryInfo)
            Dim isInPeopleFolder As Boolean = IsInPeopleDirectory(directoryInfo)

            For Each imageFile As FileInfo In imageFiles
                Try
                    Dim spriteSheetImage As Image = Await Task.Run(Function() Image.FromFile(imageFile.FullName))

                    Dim frameWidth As Integer
                    Dim frameHeight As Integer

                    If isInBossesFolder Then
                        frameWidth = 96
                        frameHeight = 96

                        Dim firstFrame As Image = ExtractFirstFrame(spriteSheetImage, frameWidth, frameHeight, frameIndex:=1)

                        spriteSheetImage.Dispose()

                        Dim displayName As String = imageFile.Name

                        Invoke(Sub()
                                   Dim imageItem As New ImageItem() With {
                               .Filename = displayName,
                               .FilePath = imageFile.FullName,
                               .Width = frameWidth + 10,
                               .Height = frameHeight + 30,
                               .Image = firstFrame,
                               .IsSpriteSheet = True,
                               .FrameWidth = frameWidth,
                               .FrameHeight = frameHeight
                           }

                                   AddHandler imageItem.ImageItemMouseDownEvent, AddressOf ImageItem_MouseDown
                                   AddHandler imageItem.ImageItemMouseMoveEvent, AddressOf ImageItem_MouseMove
                                   AddHandler imageItem.ImageItemMouseUpEvent, AddressOf ImageItem_MouseUp

                                   FLPImages.Controls.Add(imageItem)
                               End Sub)
                    ElseIf isInPeopleFolder Then
                        frameWidth = 32
                        frameHeight = 32

                        Dim firstFrame As Image = ExtractFirstFrame(spriteSheetImage, frameWidth, frameHeight)

                        spriteSheetImage.Dispose()

                        Dim displayName As String = imageFile.Name

                        Invoke(Sub()
                                   Dim imageItem As New ImageItem() With {
                               .Filename = displayName,
                               .FilePath = imageFile.FullName,
                               .Width = 100,
                               .Height = 120,
                               .Image = firstFrame,
                               .IsSpriteSheet = True,
                               .FrameWidth = frameWidth,
                               .FrameHeight = frameHeight
                           }

                                   AddHandler imageItem.ImageItemMouseDownEvent, AddressOf ImageItem_MouseDown
                                   AddHandler imageItem.ImageItemMouseMoveEvent, AddressOf ImageItem_MouseMove
                                   AddHandler imageItem.ImageItemMouseUpEvent, AddressOf ImageItem_MouseUp

                                   FLPImages.Controls.Add(imageItem)
                               End Sub)
                    Else
                        frameWidth = spriteSheetImage.Width
                        frameHeight = spriteSheetImage.Height

                        Dim firstFrame As Image = New Bitmap(spriteSheetImage)

                        spriteSheetImage.Dispose()

                        Dim displayName As String = imageFile.Name

                        Invoke(Sub()
                                   Dim imageItem As New ImageItem() With {
                               .Filename = displayName,
                               .FilePath = imageFile.FullName,
                               .Width = 100,
                               .Height = 120,
                               .Image = firstFrame,
                               .IsSpriteSheet = False,
                               .FrameWidth = frameWidth,
                               .FrameHeight = frameHeight
                           }

                                   AddHandler imageItem.ImageItemMouseDownEvent, AddressOf ImageItem_MouseDown
                                   AddHandler imageItem.ImageItemMouseMoveEvent, AddressOf ImageItem_MouseMove
                                   AddHandler imageItem.ImageItemMouseUpEvent, AddressOf ImageItem_MouseUp

                                   FLPImages.Controls.Add(imageItem)
                               End Sub)
                    End If
                Catch ex As Exception
                    Dim unused1 = MessageBox.Show("Error processing image " & imageFile.Name & ": " & ex.Message)
                End Try
            Next
        Catch ex As Exception
            Dim unused = MessageBox.Show("Error loading images: " & ex.Message)
        End Try
    End Function

    Private Function IsInBossesDirectory(directory As DirectoryInfo) As Boolean
        Dim bossesDirectoryPath As String = Path.Combine(GetProjectDirectory() + "Decor", "People", "Boss")
        bossesDirectoryPath = Path.GetFullPath(bossesDirectoryPath).TrimEnd(Path.DirectorySeparatorChar).ToLowerInvariant()
        Dim currentDirectoryPath As String = directory.FullName.TrimEnd(Path.DirectorySeparatorChar).ToLowerInvariant()
        Return String.Equals(currentDirectoryPath, bossesDirectoryPath, StringComparison.OrdinalIgnoreCase)
    End Function

    Private Function IsInPeopleDirectory(directory As DirectoryInfo) As Boolean
        Dim peopleDirectoryPath As String = Path.Combine(GetProjectDirectory() + "Decor", "People")
        peopleDirectoryPath = Path.GetFullPath(peopleDirectoryPath).TrimEnd(Path.DirectorySeparatorChar).ToLowerInvariant()
        Dim currentDirectoryPath As String = directory.FullName.TrimEnd(Path.DirectorySeparatorChar).ToLowerInvariant()
        Return currentDirectoryPath.StartsWith(peopleDirectoryPath, StringComparison.OrdinalIgnoreCase)
    End Function

    Private Function ExtractFirstFrame(spriteSheet As Image, frameWidth As Integer, frameHeight As Integer, Optional frameIndex As Integer = 0) As Image
        Dim framesInRow As Integer = spriteSheet.Width \ frameWidth

        If frameIndex < 0 OrElse frameIndex >= framesInRow Then
            frameIndex = 0
        End If

        Dim sourceRect As New Rectangle(frameIndex * frameWidth, 0, frameWidth, frameHeight)

        Dim firstFrame As New Bitmap(frameWidth, frameHeight, PixelFormat.Format32bppArgb)
        Using g As Graphics = Graphics.FromImage(firstFrame)
            g.DrawImage(spriteSheet, New Rectangle(0, 0, frameWidth, frameHeight), sourceRect, GraphicsUnit.Pixel)
        End Using

        Return firstFrame
    End Function

    Private Function ExtractFrameAt(spriteSheet As Image, frameWidth As Integer, frameHeight As Integer, frameIndex As Integer) As Image
        Dim framesInRow As Integer = spriteSheet.Width \ frameWidth

        If frameIndex < 0 OrElse frameIndex >= framesInRow Then
            frameIndex = 0
        End If

        Dim sourceRect As New Rectangle(frameIndex * frameWidth, 0, frameWidth, frameHeight)

        Dim frameImage As New Bitmap(frameWidth, frameHeight)
        Using g As Graphics = Graphics.FromImage(frameImage)
            g.DrawImage(spriteSheet, New Rectangle(0, 0, frameWidth, frameHeight), sourceRect, GraphicsUnit.Pixel)
        End Using

        Return frameImage
    End Function

    Private Sub PopulateTreeView(rootDirectory As String)
        TrvFiles.Nodes.Clear()
        Dim rootDirectoryInfo As New DirectoryInfo(rootDirectory)
        Dim rootNode As New TreeNode(rootDirectoryInfo.Name) With {.Tag = rootDirectoryInfo}
        Dim unused = TrvFiles.Nodes.Add(rootNode)
        AddDirectories(rootDirectoryInfo, rootNode)
    End Sub

    Private Sub AddDirectories(directoryInfo As DirectoryInfo, node As TreeNode)
        For Each directory As DirectoryInfo In directoryInfo.GetDirectories()
            Dim directoryNode As New TreeNode(directory.Name) With {.Tag = directory}
            Dim unused = node.Nodes.Add(directoryNode)
            AddDirectories(directory, directoryNode)
        Next
    End Sub

    Private Async Sub TrvFiles_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TrvFiles.AfterSelect
        FLPImages.Controls.Clear()
        Dim selectedNode As TreeNode = e.Node
        If TypeOf selectedNode.Tag Is DirectoryInfo Then
            Dim directoryInfo As DirectoryInfo = CType(selectedNode.Tag, DirectoryInfo)
            Await LoadImagesAsync(directoryInfo)
        End If
    End Sub

#End Region

#Region " Mouse Events for Dragging Images "

    Private Sub ImageItem_MouseDown(sender As Object, e As MouseEventArgs)
        If e.Button = MouseButtons.Left Then
            Dim dragSize As Size = SystemInformation.DragSize
            dragBoxFromMouseDown = New Rectangle(New Point(e.X - (dragSize.Width \ 2),
                                                       e.Y - (dragSize.Height \ 2)),
                                             dragSize)
        Else
            dragBoxFromMouseDown = Rectangle.Empty
        End If
    End Sub

    Private Sub ImageItem_MouseMove(sender As Object, e As MouseEventArgs)
        If (e.Button And MouseButtons.Left) = MouseButtons.Left Then
            If dragBoxFromMouseDown <> Rectangle.Empty AndAlso Not dragBoxFromMouseDown.Contains(e.Location) Then
                Dim imageItem As ImageItem = CType(sender, ImageItem)
                Dim image As Image = imageItem.Image

                If image IsNot Nothing AndAlso image.Width > 0 AndAlso image.Height > 0 Then
                    Try
                        Dim cursor As Cursor = CreateCursorFromImage(image)
                        Cursor.Current = cursor

                        Dim dataObj As New DataObject()
                        dataObj.SetData(GetType(Bitmap), image)
                        Dim imageFilePath As String = imageItem.FilePath
                        dataObj.SetData("ImageFilePath", imageFilePath)
                        dataObj.SetData("IsSpriteSheet", imageItem.IsSpriteSheet)

                        dataObj.SetData("FrameWidth", imageItem.FrameWidth)
                        dataObj.SetData("FrameHeight", imageItem.FrameHeight)

                        Dim unused2 = imageItem.DoDragDrop(dataObj, DragDropEffects.Copy)
                        Cursor.Current = Cursors.Default

                        cursor.Dispose()
                    Catch ex As Exception
                        Dim unused1 = MessageBox.Show("Error creating cursor: " & ex.Message)
                        Return
                    End Try
                Else
                    Dim unused = MessageBox.Show("Error: The image is invalid or has been disposed.")
                    Return
                End If
                dragBoxFromMouseDown = Rectangle.Empty
            End If
        End If
    End Sub

    Private Sub ImageItem_MouseUp(sender As Object, e As MouseEventArgs)
        dragBoxFromMouseDown = Rectangle.Empty
    End Sub

    Private Function CreateCursorFromImage(image As Image) As Cursor
        Try
            If image Is Nothing Then
                Throw New ArgumentNullException(NameOf(image), "Image cannot be null.")
            End If

            If image.Width = 0 OrElse image.Height = 0 Then
                Throw New ArgumentException("Image dimensions are invalid.")
            End If

            Dim cursorSize As Integer = 32
            Using bitmap As New Bitmap(cursorSize, cursorSize, PixelFormat.Format32bppArgb)
                Using g As Graphics = Graphics.FromImage(bitmap)
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic
                    g.DrawImage(image, New Rectangle(0, 0, cursorSize, cursorSize))
                End Using

                Dim iconHandle As IntPtr = bitmap.GetHicon()

                Dim cursor As New Cursor(iconHandle)

                Dim unused1 = DestroyIcon(iconHandle)

                Return cursor
            End Using
        Catch ex As Exception
            Dim unused = MessageBox.Show("Error creating cursor: " & ex.Message)
            Return Cursors.Default
        End Try
    End Function

    <DllImport("user32.dll", CharSet:=CharSet.Auto)>
    Private Shared Function DestroyIcon(ByVal hIcon As IntPtr) As Boolean
    End Function

    Private Sub CanvasModified_Handler()
        isModified = True
    End Sub

#End Region

#Region " CTMTrvFIles "

    Private Sub MnuCollapse_Click(sender As Object, e As EventArgs) Handles MnuCollapse.Click
        Dim selectedNode As TreeNode = TrvFiles.SelectedNode
        If selectedNode IsNot Nothing Then
            CollapseAllNodes(selectedNode)
        Else
            Dim unused = MessageBox.Show("Please select a node to collapse.", "Collapse Node", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    Private Sub MnuExpand_Click(sender As Object, e As EventArgs) Handles MnuExpand.Click
        Dim selectedNode As TreeNode = TrvFiles.SelectedNode
        If selectedNode IsNot Nothing Then
            ExpandAllNodes(selectedNode)
        Else
            Dim unused = MessageBox.Show("Please select a node to expand.", "Expand Node", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    Private Sub ExpandAllNodes(node As TreeNode)
        node.Expand()
        For Each childNode As TreeNode In node.Nodes
            ExpandAllNodes(childNode)
        Next
    End Sub

    Private Sub CollapseAllNodes(node As TreeNode)
        For Each childNode As TreeNode In node.Nodes
            CollapseAllNodes(childNode)
        Next
        node.Collapse()
    End Sub

#End Region

#Region " Search "

    Private Async Sub CboSearch_KeyDown(sender As Object, e As KeyEventArgs)
        If e.KeyCode = Keys.Enter Then
            Dim searchTerm As String = cboSearch.Text.Trim()
            If Not String.IsNullOrEmpty(searchTerm) Then
                Await PerformSearch(searchTerm)
                e.Handled = True
            End If
        End If
    End Sub

    Private Async Sub CboSearch_SelectedIndexChanged(sender As Object, e As EventArgs)
        If isUpdatingComboBox Then
            Return
        End If
        Dim searchTerm As String = cboSearch.SelectedItem.ToString()
        If Not String.IsNullOrEmpty(searchTerm) Then
            Await PerformSearch(searchTerm)
        End If
    End Sub

    Private Async Function PerformSearch(searchTerm As String) As Task
        If searchCancellationTokenSource IsNot Nothing AndAlso Not searchCancellationTokenSource.IsCancellationRequested Then
            searchCancellationTokenSource.Cancel()
        End If

        searchCancellationTokenSource = New CancellationTokenSource()
        Dim token As CancellationToken = searchCancellationTokenSource.Token

        FLPImages.Controls.Clear()

        PrgSearchProgress.Visible = True
        PrgSearchProgress.Style = ProgressBarStyle.Marquee

        Try
            Dim matchingFiles As New List(Of FileInfo)
            Await Task.Run(Sub()
                               SearchAllDirectories(searchTerm, matchingFiles, token)
                           End Sub)

            PrgSearchProgress.Style = ProgressBarStyle.Continuous
            PrgSearchProgress.Minimum = 0
            PrgSearchProgress.Maximum = Math.Min(matchingFiles.Count, MaxImagesToDisplay)
            PrgSearchProgress.Value = 0

            Dim progressHandler As New Progress(Of ImageItem)(Sub(imageItem)
                                                                  FLPImages.Controls.Add(imageItem)
                                                              End Sub)

            Await LoadImagesFromFilesAsync(matchingFiles, token, progressHandler)

            If Not token.IsCancellationRequested Then
                AddSearchToRecent(searchTerm)
            End If
        Catch ex As OperationCanceledException
        Finally
            PrgSearchProgress.Visible = False
        End Try
    End Function

    Private Sub SearchAllDirectories(searchTerm As String, matchingFiles As List(Of FileInfo), token As CancellationToken)
        Dim directoriesToSearch As New ConcurrentBag(Of DirectoryInfo)

        For Each rootNode As TreeNode In TrvFiles.Nodes
            If TypeOf rootNode.Tag Is DirectoryInfo Then
                directoriesToSearch.Add(CType(rootNode.Tag, DirectoryInfo))
            End If
        Next

        Dim unused = Parallel.ForEach(directoriesToSearch, Sub(directory)
                                                               If token.IsCancellationRequested Then Return
                                                               SearchDirectory(directory, searchTerm, matchingFiles, token)
                                                           End Sub)
    End Sub

    Private Sub SearchDirectory(directory As DirectoryInfo, searchTerm As String, matchingFiles As List(Of FileInfo), token As CancellationToken)
        If token.IsCancellationRequested Then Return

        Try
            Dim imageFiles As New List(Of FileInfo)
            For Each extension As String In imageExtensions
                imageFiles.AddRange(directory.GetFiles($"*{extension}", SearchOption.TopDirectoryOnly))
            Next

            For Each imageFile As FileInfo In imageFiles
                If token.IsCancellationRequested Then Return
                If imageFile.Name.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase) >= 0 Then
                    SyncLock matchingFiles
                        matchingFiles.Add(imageFile)
                    End SyncLock
                End If
            Next

            For Each subDirectory As DirectoryInfo In directory.GetDirectories()
                If token.IsCancellationRequested Then Return
                SearchDirectory(subDirectory, searchTerm, matchingFiles, token)
            Next
        Catch ex As UnauthorizedAccessException
        End Try
    End Sub

    Private Sub SearchTreeNode(node As TreeNode, searchTerm As String, matchingFiles As List(Of FileInfo))
        If TypeOf node.Tag Is DirectoryInfo Then
            Dim directoryInfo As DirectoryInfo = CType(node.Tag, DirectoryInfo)
            Dim imageFiles As List(Of FileInfo) = GetImageFilesFromDirectory(directoryInfo)

            For Each imageFile As FileInfo In imageFiles
                If imageFile.Name.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase) >= 0 Then
                    matchingFiles.Add(imageFile)
                End If
            Next

            For Each childNode As TreeNode In node.Nodes
                SearchTreeNode(childNode, searchTerm, matchingFiles)
            Next
        End If
    End Sub

    Private Function GetImageFilesFromDirectory(directoryInfo As DirectoryInfo) As List(Of FileInfo)
        Dim imageExtensions() As String = {".jpg", ".jpeg", ".png", ".bmp", ".gif"}
        Dim imageFiles As New List(Of FileInfo)()

        For Each extension As String In imageExtensions
            imageFiles.AddRange(directoryInfo.GetFiles($"*{extension}", SearchOption.TopDirectoryOnly))
        Next

        Return imageFiles
    End Function

    Private Async Function LoadImagesFromFilesAsync(imageFiles As List(Of FileInfo), token As CancellationToken, progress As IProgress(Of ImageItem)) As Task
        Dim imagesToLoad = imageFiles.Take(MaxImagesToDisplay).ToList()
        Dim loadedImagesCount As Integer = 0

        Invoke(Sub()
                   PrgSearchProgress.Maximum = imagesToLoad.Count
                   PrgSearchProgress.Value = 0
               End Sub)

        For Each imageFile As FileInfo In imagesToLoad
            If token.IsCancellationRequested Then Exit For
            Try
                Dim image As Image = Await Task.Run(Function() Image.FromFile(imageFile.FullName), token)

                Dim imageItem As New ImageItem() With {
                .Image = image,
                .Filename = imageFile.Name,
                .FilePath = imageFile.FullName,
                .Width = 100,
                .Height = 120
            }

                AddHandler imageItem.ImageItemMouseDownEvent, AddressOf ImageItem_MouseDown
                AddHandler imageItem.ImageItemMouseMoveEvent, AddressOf ImageItem_MouseMove
                AddHandler imageItem.ImageItemMouseUpEvent, AddressOf ImageItem_MouseUp

                progress.Report(imageItem)

                loadedImagesCount += 1
                Invoke(Sub()
                           PrgSearchProgress.Value = loadedImagesCount
                       End Sub)
            Catch ex As Exception
            End Try
        Next
    End Function

    Private Sub AddSearchToRecent(searchTerm As String)
        If recentSearches.Contains(searchTerm) Then
            Dim unused1 = recentSearches.Remove(searchTerm)
        End If
        recentSearches.Insert(0, searchTerm)

        If recentSearches.Count > MaxSearches Then
            recentSearches.RemoveAt(recentSearches.Count - 1)
        End If

        isUpdatingComboBox = True
        cboSearch.Items.Clear()
        For Each term As String In recentSearches
            Dim unused = cboSearch.Items.Add(term)
        Next
        isUpdatingComboBox = False
    End Sub

#End Region

#Region " Zoom "

    Private Sub PicCanvas_ZoomLevelChanged(zoomLevel As Single) Handles PicCanvas.ZoomLevelChanged
        lblZoom.Text = "Zoom: " & (zoomLevel * 100).ToString("0.##") & "%"
    End Sub

#End Region

#Region " ToolStrip "

    Private Sub BtnZoomToFit_Click(sender As Object, e As EventArgs) Handles BtnZoomToFit.Click
        PicCanvas.ZoomToFit()
    End Sub

    Private Sub CboDimensions_SelectedIndexChanged(sender As Object, e As EventArgs)
        Dim selectedText As String = CboDimensions.SelectedItem.ToString()
        Dim dimensions() As String = selectedText.Split("x"c)
        If dimensions.Length = 2 Then
            Dim size As Integer
            If Integer.TryParse(dimensions(0).Trim(), size) Then
                PicCanvas.GridSize = size
                PicCanvas.SnapAllTilesToGrid()
            End If
        End If
    End Sub

    Private Sub CboMapSize_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CboMapSize.SelectedIndexChanged
        Dim selectedText As String = CboMapSize.SelectedItem.ToString()
        Dim dimensions() As String = selectedText.Split("x"c)
        If dimensions.Length = 2 Then
            Dim width As Integer
            Dim height As Integer
            If Integer.TryParse(dimensions(0).Trim(), width) AndAlso Integer.TryParse(dimensions(1).Trim(), height) Then
                PicCanvas.SetMapSize(width, height)
            End If
        End If
    End Sub

#End Region

#Region " Save and Load Functionality "

    Private Sub MnuSave_Click(sender As Object, e As EventArgs) Handles MnuSave.Click
        If String.IsNullOrEmpty(currentFileName) Then
            MnuSaveAs_Click(sender, e)
        Else
            SaveCanvas(currentFileName)
        End If
    End Sub

    Private Sub MnuSaveAs_Click(sender As Object, e As EventArgs) Handles MnuSaveAs.Click
        Using sfd As New SaveFileDialog()
            sfd.Filter = "Map Files (*.map)|*.map|All Files (*.*)|*.*"
            sfd.InitialDirectory = MapPath ' Use the default directory path

            If sfd.ShowDialog() = DialogResult.OK Then
                currentFileName = sfd.FileName
                SaveCanvas(currentFileName)
            End If
        End Using
    End Sub

    Private Sub MnuLoad_Click(sender As Object, e As EventArgs) Handles MnuLoad.Click
        If isModified Then
            Dim result = MessageBox.Show("Do you want to save changes?", "Save Changes", MessageBoxButtons.YesNoCancel)
            If result = DialogResult.Yes Then
                MnuSave_Click(sender, e)
            ElseIf result = DialogResult.Cancel Then
                Return
            End If
        End If

        Using ofd As New OpenFileDialog()
            ofd.Filter = "Map Files (*.map)|*.map|All Files (*.*)|*.*"
            ofd.InitialDirectory = MapPath ' Use the default directory path

            If ofd.ShowDialog() = DialogResult.OK Then
                currentFileName = ofd.FileName
                LoadCanvas(currentFileName)
            End If
        End Using
    End Sub
    Private Sub SaveCanvas(fileName As String)
        Dim canvasData As New CanvasData With {
        .GridSize = PicCanvas.GridSize,
        .MapSize = PicCanvas.MapSize,
        .MapTiles = New List(Of MapTileData)()
    }

        For Each tile As MapTile In PicCanvas.Tiles
            Dim tileData As New MapTileData With {
            .ImageFilePath = tile.ImageFilePath,
            .Position = tile.Position,
            .Size = tile.Size,
            .OriginalSize = tile.OriginalSize,
            .IsAnimated = tile.IsAnimated,
            .AnimationInterval = tile.AnimationInterval,
            .RotationAngle = tile.RotationAngle,
            .IsFlippedHorizontally = tile.IsFlippedHorizontally,
            .IsFlippedVertically = tile.IsFlippedVertically,
            .IsLocked = tile.IsLocked,
            .FrameWidth = tile.FrameWidth,
            .FrameHeight = tile.FrameHeight,
            .IsWalkable = tile.IsWalkable,
            .IsGrouped = tile.IsGrouped,
            .OriginalTiles = New List(Of MapTileData)(),
            .AnimationFramesData = New List(Of String)()
        }

            ' Set ImageData for regular tiles
            If tile.Image IsNot Nothing Then
                tileData.ImageData = ImageToBase64(tile.Image)
            End If

            ' Set AnimationFramesData for animated tiles
            If tile.IsAnimated AndAlso tile.AnimationFrames IsNot Nothing Then
                For Each frame In tile.AnimationFrames
                    tileData.AnimationFramesData.Add(ImageToBase64(frame))
                Next
            End If

            ' Handle grouped tiles
            If tile.IsGrouped Then
                For Each originalTile In tile.OriginalTiles
                    Dim originalTileData As New MapTileData With {
                    .ImageFilePath = originalTile.ImageFilePath,
                    .Position = originalTile.Position,
                    .Size = originalTile.Size,
                    .OriginalSize = originalTile.OriginalSize,
                    .IsAnimated = originalTile.IsAnimated,
                    .AnimationInterval = originalTile.AnimationInterval,
                    .RotationAngle = originalTile.RotationAngle,
                    .IsFlippedHorizontally = originalTile.IsFlippedHorizontally,
                    .IsFlippedVertically = originalTile.IsFlippedVertically,
                    .IsLocked = originalTile.IsLocked,
                    .FrameWidth = originalTile.FrameWidth,
                    .FrameHeight = originalTile.FrameHeight,
                    .IsWalkable = originalTile.IsWalkable,
                    .IsGrouped = originalTile.IsGrouped
                }

                    ' Set ImageData for original tiles in the group
                    If originalTile.Image IsNot Nothing Then
                        originalTileData.ImageData = ImageToBase64(originalTile.Image)
                    End If

                    tileData.OriginalTiles.Add(originalTileData)
                Next
            End If

            canvasData.MapTiles.Add(tileData)
        Next

        Dim serializer As New XmlSerializer(GetType(CanvasData))
        Using writer As New StreamWriter(fileName)
            serializer.Serialize(writer, canvasData)
        End Using

        isModified = False
    End Sub
    Private Function ImageToBase64(image As Image) As String
        Using ms As New MemoryStream()
            image.Save(ms, ImageFormat.Png)
            Return Convert.ToBase64String(ms.ToArray())
        End Using
    End Function
    Private Sub LoadCanvas(fileName As String)
        Dim serializer As New XmlSerializer(GetType(CanvasData))
        Using reader As New StreamReader(fileName)
            Dim canvasData As CanvasData = CType(serializer.Deserialize(reader), CanvasData)

            PicCanvas.ClearTiles()

            PicCanvas.GridSize = canvasData.GridSize
            PicCanvas.SetMapSize(canvasData.MapSize.Width, canvasData.MapSize.Height)

            For Each tileData As MapTileData In canvasData.MapTiles
                Dim mapTile As MapTile

                If tileData.IsGrouped Then
                    ' Create a new grouped tile
                    Dim groupedTile As New MapTile With {
                    .Position = tileData.Position,
                    .Size = tileData.Size,
                    .OriginalSize = tileData.OriginalSize,
                    .IsGrouped = True,
                    .OriginalTiles = New List(Of MapTile)()
                }

                    ' Add the original tiles to the grouped tile
                    For Each originalTileData In tileData.OriginalTiles
                        Dim originalTile As New MapTile With {
                        .Position = originalTileData.Position,
                        .Size = originalTileData.Size,
                        .OriginalSize = originalTileData.OriginalSize,
                        .IsGrouped = originalTileData.IsGrouped
                    }

                        ' Set the image for original tiles in the group
                        If Not String.IsNullOrEmpty(originalTileData.ImageData) Then
                            originalTile.Image = Base64ToImage(originalTileData.ImageData)
                        End If

                        groupedTile.OriginalTiles.Add(originalTile)
                    Next

                    mapTile = groupedTile
                Else
                    ' Create a regular tile
                    mapTile = New MapTile With {
                    .Position = tileData.Position,
                    .Size = tileData.Size,
                    .OriginalSize = tileData.OriginalSize,
                    .IsGrouped = False
                }

                    ' Set the image for regular tiles
                    If Not String.IsNullOrEmpty(tileData.ImageData) Then
                        mapTile.Image = Base64ToImage(tileData.ImageData)
                    End If

                    ' Handle animated tiles
                    If tileData.IsAnimated AndAlso tileData.AnimationFramesData IsNot Nothing Then
                        mapTile.AnimationFrames = New List(Of Image)
                        For Each frameData In tileData.AnimationFramesData
                            Dim frameImage As Image = Base64ToImage(frameData)
                            If frameImage IsNot Nothing Then
                                mapTile.AnimationFrames.Add(frameImage)
                            End If
                        Next
                    End If
                End If

                PicCanvas.AddTile(mapTile)
            Next
        End Using

        isModified = False
    End Sub
    Private Function Base64ToImage(base64String As String) As Image
        If String.IsNullOrEmpty(base64String) Then
            Return Nothing
        End If

        Try
            Dim imageBytes() As Byte = Convert.FromBase64String(base64String)
            Using ms As New MemoryStream(imageBytes)
                Return Image.FromStream(ms)
            End Using
        Catch ex As Exception
            Return Nothing
        End Try
    End Function
    Private Sub MnuNew_Click(sender As Object, e As EventArgs) Handles MnuNew.Click
        If isModified Then
            Dim result = MessageBox.Show("Do you want to save changes?", "Save Changes", MessageBoxButtons.YesNoCancel)
            If result = DialogResult.Yes Then
                MnuSave_Click(sender, e)
            ElseIf result = DialogResult.Cancel Then
                Return
            End If
        End If

        PicCanvas.ClearTiles()
        currentFileName = ""
        isModified = False
    End Sub

    Private Sub MnuExit_Click(sender As Object, e As EventArgs) Handles MnuExit.Click
        If isModified Then
            Dim result = MessageBox.Show("Do you want to save changes?", "Save Changes", MessageBoxButtons.YesNoCancel)
            If result = DialogResult.Yes Then
                MnuSave_Click(sender, e)
            ElseIf result = DialogResult.Cancel Then
                Return
            End If
        End If
        Close()
    End Sub

#End Region

#Region " Zoom "

    Private Sub Mnu50_Click(sender As Object, e As EventArgs) Handles Mnu50.Click
        SetZoom(0.5F)
    End Sub

    Private Sub Mnu100_Click(sender As Object, e As EventArgs) Handles Mnu100.Click
        SetZoom(1.0F)
    End Sub

    Private Sub Mnu250_Click(sender As Object, e As EventArgs) Handles Mnu250.Click
        SetZoom(2.5F)
    End Sub

    Private Sub Mnu500_Click(sender As Object, e As EventArgs) Handles Mnu500.Click
        SetZoom(5.0F)
    End Sub

    Private Sub Mnu1000_Click(sender As Object, e As EventArgs) Handles Mnu1000.Click
        SetZoom(10.0F)
    End Sub

    Private Sub SetZoom(ByVal zoomLevel As Single)
        PicCanvas.ZoomLevel = zoomLevel
    End Sub

    Private Sub TrvFiles_NodeMouseClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles TrvFiles.NodeMouseClick
        If e.Button = MouseButtons.Right Then
            TrvFiles.SelectedNode = e.Node
        End If
    End Sub

    Private Sub MnuOpenInExplorer_Click(sender As Object, e As EventArgs) Handles MnuOpenInExplorer.Click
        Dim selectedNode As TreeNode = TrvFiles.SelectedNode
        If selectedNode IsNot Nothing AndAlso TypeOf selectedNode.Tag Is DirectoryInfo Then
            Dim directoryInfo As DirectoryInfo = CType(selectedNode.Tag, DirectoryInfo)
            If directoryInfo.Exists Then
                Try
                    Dim unused3 = Process.Start("explorer.exe", directoryInfo.FullName)
                Catch ex As Exception
                    Dim unused2 = MessageBox.Show("Failed to open folder: " & ex.Message)
                End Try
            Else
                Dim unused1 = MessageBox.Show("Directory does not exist.")
            End If
        Else
            Dim unused = MessageBox.Show("No directory selected.")
        End If
    End Sub

    Private Sub PicCanvas_MouseMove(sender As Object, e As MouseEventArgs) Handles PicCanvas.MouseMove
        Dim canvasPoint As Point = PicCanvas.ClientToCanvas(e.Location)
        STBMouseCoords.Text = $"X: {canvasPoint.X}, Y: {canvasPoint.Y}"
    End Sub

#End Region

#Region " Closing "

    Private Sub FrmWorld_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        SaveTreeViewState()
        SaveRecentSearches()
    End Sub

    Private Sub SaveRecentSearches()
        Dim serializer As New XmlSerializer(GetType(List(Of String)))
        Using writer As New StreamWriter("RecentSearches.xml")
            serializer.Serialize(writer, recentSearches)
        End Using
    End Sub

    Private Sub SaveTreeViewState()
        Dim state As New TreeViewState()

        For Each node As TreeNode In TrvFiles.Nodes
            SaveExpandedNodes(node, state)
        Next

        If TrvFiles.SelectedNode IsNot Nothing Then
            state.SelectedNodePath = TrvFiles.SelectedNode.FullPath
        End If

        Dim serializer As New XmlSerializer(GetType(TreeViewState))
        Using writer As New StreamWriter("TreeViewState.xml")
            serializer.Serialize(writer, state)
        End Using
    End Sub

    Private Sub SaveExpandedNodes(node As TreeNode, state As TreeViewState)
        If node.IsExpanded Then
            state.ExpandedNodes.Add(node.FullPath)
        End If
        For Each childNode As TreeNode In node.Nodes
            SaveExpandedNodes(childNode, state)
        Next
    End Sub

#End Region

#Region " Undo Redo "

    Private Sub BtnUndo_Click(sender As Object, e As EventArgs) Handles BtnUndo.Click
        PicCanvas.Undo()
    End Sub

    Private Sub BtnRedo_Click(sender As Object, e As EventArgs) Handles BtnRedo.Click
        PicCanvas.Redo()
    End Sub
    Private Sub AddAction(action As MapAction)
        undoStack.Push(action)
        redoStack.Clear()
    End Sub

    Private Sub Undo()
        If undoStack.Count > 0 Then
            Dim action As MapAction = undoStack.Pop()
            action.Undo()
            redoStack.Push(action)
        End If
    End Sub

    Private Sub Redo()
        If redoStack.Count > 0 Then
            Dim action As MapAction = redoStack.Pop()
            action.Execute()
            undoStack.Push(action)
        End If
    End Sub

#End Region

#Region " Other "

    Private Sub PicCanvas_TileSelected(selectedTile As MapTile)
        STBSize.Text = If(selectedTile IsNot Nothing,
            $"Original Size {selectedTile.OriginalSize.Width}, {selectedTile.OriginalSize.Height}: Current Size {selectedTile.Size.Width}, {selectedTile.Size.Height}",
            "")
        UpdateSTBSize(selectedTile)
    End Sub

    Private Sub PicCanvas_TileSizeChanged(selectedTile As MapTile)
        UpdateSTBSize(selectedTile)
        AddAction(New MoveTileAction(selectedTile, PicCanvas, selectedTile.Position, selectedTile.Position))
    End Sub

    Private Sub UpdateSTBSize(selectedTile As MapTile)
        STBSize.Text = If(selectedTile IsNot Nothing,
            $"Original Size {selectedTile.OriginalSize.Width}, {selectedTile.OriginalSize.Height}: Current Size {selectedTile.Size.Width}, {selectedTile.Size.Height}",
            "")
    End Sub

    Private Sub ChkShowPathing_CheckedChanged(sender As Object, e As EventArgs) Handles chkShowPathing.CheckedChanged
        ' Update the ShowPathing property in MapCanvas
        PicCanvas.ShowPathing = chkShowPathing.Checked
        ' Refresh the canvas to show/hide the walkable overlay
        PicCanvas.Invalidate()
    End Sub
#End Region

End Class

Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging

Public Class MapCanvas
    Inherits UserControl

    Public Sub New()
        InitializeComponent()
        InitializeControl()
    End Sub

#Region " Variables And Properties "
    Private actionAdded As Boolean = False
    Private undoRedoManager As New UndoRedoManager()
    Private _tiles As New List(Of MapTile)

    Private PicCanvas As MapCanvas
    Private undoStack As New Stack(Of MapAction)
    Private redoStack As New Stack(Of MapAction)

    Private ctrlClickTile As MapTile = Nothing

    Private Const DragThreshold As Integer = 4
    Private isCtrlClick As Boolean = False
    Private mouseDownLocation As Point

    Public Event TileSizeChanged(selectedTile As MapTile)

    Public Event TileSelected(selectedTile As MapTile)

    Private contextMenuTile As MapTile = Nothing
    Private animationTimer As System.Windows.Forms.Timer

    Public Event ZoomLevelChanged(zoomLevel As Single)

    Private selectedTile As MapTile = Nothing

    Private dragging As Boolean = False
    Private resizing As Boolean = False

    Private initialTileState As MapTile
    Private initialTilePosition As Point
    Private initialTileSize As Size
    Private initialMousePosition As Point

    Private isSelecting As Boolean = False

    Private selectionStartPoint As Point
    Private selectionEndPoint As Point
    Private selectionRectangle As Rectangle

    Private selectedTiles As New List(Of MapTile)

    Private initialSelectedTilesBounds As Rectangle

    Private initialSelectedTilesPositionsAndSizes As New List(Of Tuple(Of MapTile, Point, Size))

    Private isPanning As Boolean = False

    Private panStartPoint As Point
    Private scrollStartPoint As Point
    Private hasPanned As Boolean = False

    Private _gridSize As Integer = 32

    Private snappingEnabled As Boolean = True

    Private _showGrid As Boolean = True

    Private _mapWidth As Integer = 15000

    Private _mapHeight As Integer = 10000

    Private _zoomLevel As Single = 1.0F

    Public Event CanvasModified()
    Public Property ShowPathing As Boolean = False
    Public Property GridSize As Integer
        Get
            Return _gridSize
        End Get
        Set(value As Integer)
            If value > 0 Then
                _gridSize = value
                Invalidate()
            End If
        End Set
    End Property

    Public Property ShowGrid As Boolean
        Get
            Return _showGrid
        End Get
        Set(value As Boolean)
            _showGrid = value
            Invalidate()
        End Set
    End Property

    Public ReadOnly Property Tiles As List(Of MapTile)
        Get
            Return _tiles
        End Get
    End Property

    Public Property ZoomLevel As Single
        Get
            Return _zoomLevel
        End Get
        Set(value As Single)
            If value <= 0 Then
                value = 0.01F
            End If

            If _zoomLevel <> value Then
                Dim oldZoomLevel As Single = _zoomLevel
                _zoomLevel = value
                AdjustScrollPosition(oldZoomLevel, Nothing)
                UpdateScrollBars()
                Invalidate()
                RaiseEvent ZoomLevelChanged(_zoomLevel)
            End If
        End Set
    End Property

    Public ReadOnly Property MapWidth As Integer
        Get
            Return _mapWidth
        End Get
    End Property

    Public ReadOnly Property MapHeight As Integer
        Get
            Return _mapHeight
        End Get
    End Property

    Public ReadOnly Property MapSize As Size
        Get
            Return New Size(_mapWidth, _mapHeight)
        End Get
    End Property

#End Region

#Region " Initialization and Setup "

    Private Sub InitializeControl()
        DoubleBuffered = True

        SetStyle(ControlStyles.AllPaintingInWmPaint Or
             ControlStyles.OptimizedDoubleBuffer Or
             ControlStyles.ResizeRedraw Or
             ControlStyles.UserPaint Or
             ControlStyles.Selectable, True)

        UpdateStyles()

        AutoScroll = True

        TabStop = True

        ContextMenuStrip = Nothing

        animationTimer = New System.Windows.Forms.Timer With {
            .Interval = 50
        }
        AddHandler animationTimer.Tick, AddressOf AnimationTimer_Tick
        animationTimer.Start()
    End Sub

#End Region

#Region " Drawing Methods "

    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        MyBase.OnPaint(e)

        Dim g As Graphics = e.Graphics

        g.Clear(Color.White)

        g.InterpolationMode = InterpolationMode.NearestNeighbor
        g.PixelOffsetMode = PixelOffsetMode.Half
        g.SmoothingMode = SmoothingMode.None

        Dim state As GraphicsState = g.Save()

        g.TranslateTransform(AutoScrollPosition.X, AutoScrollPosition.Y)
        g.ScaleTransform(ZoomLevel, ZoomLevel)

        g.PixelOffsetMode = PixelOffsetMode.None

        DrawGrid(g)
        DrawTiles(g)

        g.Restore(state)

        If isSelecting Then
            DrawSelectionRectangle(g)
        End If

        If selectedTiles.Count > 0 Then
            If selectedTiles.Count = 1 Then
                DrawResizeHandles(g, selectedTiles(0))
            Else
                DrawGroupResizeHandles(g)
            End If
        End If
    End Sub

    Private Sub DrawTiles(g As Graphics)
        For Each tile In _tiles
            If tile.Image Is Nothing Then
                Continue For
            End If

            Dim tileRect As New Rectangle(Math.Round(tile.Position.X),
                                      Math.Round(tile.Position.Y),
                                      Math.Round(tile.Size.Width),
                                      Math.Round(tile.Size.Height))

            g.DrawImage(tile.Image, tileRect)

            ' Draw the walkable overlay if the tile is walkable AND ShowPathing is True
            If tile.IsWalkable AndAlso ShowPathing Then
                Using overlayBrush As New SolidBrush(Color.FromArgb(128, Color.LightPink))
                    g.FillRectangle(overlayBrush, tileRect)
                End Using
            End If

            If tile.Selected Then
                Using pen As New Pen(Color.Blue)
                    pen.DashStyle = DashStyle.Dash
                    g.DrawRectangle(pen, tileRect)
                End Using
            End If
        Next
    End Sub
    Private Sub DrawGrid(g As Graphics)
        If Not _showGrid Then Exit Sub

        Using pen As New Pen(Color.LightGray)
            pen.Width = 1 / ZoomLevel

            Dim visibleRect As Rectangle = GetVisibleCanvasRectangle()

            Dim startX As Integer = visibleRect.Left - (visibleRect.Left Mod _gridSize)
            Dim startY As Integer = visibleRect.Top - (visibleRect.Top Mod _gridSize)

            For x As Integer = startX To visibleRect.Right Step _gridSize
                g.DrawLine(pen, x, visibleRect.Top, x, visibleRect.Bottom)
            Next

            For y As Integer = startY To visibleRect.Bottom Step _gridSize
                g.DrawLine(pen, visibleRect.Left, y, visibleRect.Right, y)
            Next
        End Using

        DrawGridBorder(g)
    End Sub

    Private Sub DrawGridBorder(g As Graphics)
        Dim gridRect As New Rectangle(0, 0, _mapWidth, _mapHeight)

        Using pen As New Pen(Color.Black)
            pen.Width = 4 / ZoomLevel
            g.DrawRectangle(pen, gridRect)
        End Using
    End Sub

    Private Sub DrawSelectionRectangle(g As Graphics)
        Using selectionPen As New Pen(Color.Red)
            selectionPen.DashStyle = Drawing2D.DashStyle.Dash
            Dim rect As Rectangle = GetSelectionRectangle()
            Dim screenRect As Rectangle = CanvasToClientRect(rect)
            g.DrawRectangle(selectionPen, screenRect)
        End Using
    End Sub

    Private Sub DrawResizeHandles(g As Graphics, tile As MapTile)
        Dim handleSize As Integer = 6
        Dim tileRect As New Rectangle(tile.Position, tile.Size)
        Dim screenRect As Rectangle = CanvasToClientRect(tileRect)

        Using brush As New SolidBrush(Color.White)
            Using pen As New Pen(Color.Black)
                DrawHandle(g, brush, pen, screenRect.Left - (handleSize \ 2), screenRect.Top - (handleSize \ 2), handleSize)
                DrawHandle(g, brush, pen, screenRect.Right - (handleSize \ 2), screenRect.Top - (handleSize \ 2), handleSize)
                DrawHandle(g, brush, pen, screenRect.Left - (handleSize \ 2), screenRect.Bottom - (handleSize \ 2), handleSize)
                DrawHandle(g, brush, pen, screenRect.Right - (handleSize \ 2), screenRect.Bottom - (handleSize \ 2), handleSize)
            End Using
        End Using
    End Sub

    Private Sub DrawGroupResizeHandles(g As Graphics)
        Dim handleSize As Integer = 6
        Dim bounds = GetSelectedTilesBounds()
        Dim screenRect As Rectangle = CanvasToClientRect(bounds)

        Using brush As New SolidBrush(Color.White)
            Using pen As New Pen(Color.Black)
                DrawHandle(g, brush, pen, screenRect.Left - (handleSize \ 2), screenRect.Top - (handleSize \ 2), handleSize)
                DrawHandle(g, brush, pen, screenRect.Right - (handleSize \ 2), screenRect.Top - (handleSize \ 2), handleSize)
                DrawHandle(g, brush, pen, screenRect.Left - (handleSize \ 2), screenRect.Bottom - (handleSize \ 2), handleSize)
                DrawHandle(g, brush, pen, screenRect.Right - (handleSize \ 2), screenRect.Bottom - (handleSize \ 2), handleSize)
            End Using
        End Using
    End Sub

    Private Sub DrawHandle(g As Graphics, brush As Brush, pen As Pen, x As Integer, y As Integer, size As Integer)
        g.FillRectangle(brush, x, y, size, size)
        g.DrawRectangle(pen, x, y, size, size)
    End Sub

#End Region

#Region " Mouse Event Handlers "
    Private Sub HandleLeftMouseDown(e As MouseEventArgs, currentPoint As Point, clickedTile As MapTile)
        If clickedTile IsNot Nothing AndAlso Not clickedTile.IsLocked Then
            Dim direction As MapTile.ResizeDirections = GetResizeDirection(clickedTile, currentPoint)
            If direction <> MapTile.ResizeDirections.None Then
                initialTileSize = clickedTile.Size
                initialTilePosition = clickedTile.Position
                StartSingleTileResizing(clickedTile, currentPoint, direction)
            Else
                initialTilePosition = clickedTile.Position
                If selectedTiles.Contains(clickedTile) Then
                    For Each tile In selectedTiles
                        tile.InitialPosition = tile.Position
                    Next
                    initialMousePosition = currentPoint
                    dragging = True
                    Refresh()
                Else
                    DeselectAllTiles()
                    selectedTile = clickedTile
                    selectedTile.Selected = True
                    selectedTiles.Clear()
                    selectedTiles.Add(selectedTile)

                    selectedTile.InitialPosition = selectedTile.Position
                    initialMousePosition = currentPoint
                    dragging = True
                    Refresh()
                End If
            End If
            actionAdded = False
        Else
            StartSelection(currentPoint)
        End If
    End Sub
    Private Sub HandleRightMouseUp(e As MouseEventArgs)
        Dim currentPoint As Point = ClientToCanvas(e.Location)
        contextMenuTile = GetTileAtPoint(currentPoint, includeLockedTiles:=True)

        If contextMenuTile IsNot Nothing Then
            ' If the clicked tile is not already selected, select it
            If Not contextMenuTile.Selected Then
                DeselectAllTiles()
                contextMenuTile.Selected = True
                selectedTiles.Clear()
                selectedTiles.Add(contextMenuTile)
                selectedTile = contextMenuTile

                RaiseEvent TileSelected(selectedTile)
            End If

            ' Show the context menu at the mouse position
            CTMMenu.Show(Me, e.Location)
        Else
            ' If no tile was clicked, deselect all tiles
            DeselectAllTiles()
        End If

        Refresh()
    End Sub
    Private Sub HandleDragging(currentPoint As Point)
        Dim deltaX As Integer = currentPoint.X - initialMousePosition.X
        Dim deltaY As Integer = currentPoint.Y - initialMousePosition.Y

        For Each tile In selectedTiles
            Dim initialPos As Point = tile.InitialPosition
            Dim newPos As New Point(initialPos.X + deltaX, initialPos.Y + deltaY)

            If snappingEnabled AndAlso Not IsShiftKeyPressed Then
                newPos.X = CInt(Math.Round(newPos.X / _gridSize)) * _gridSize
                newPos.Y = CInt(Math.Round(newPos.Y / _gridSize)) * _gridSize
            End If

            newPos.X = Math.Max(0, Math.Min(newPos.X, _mapWidth - tile.Size.Width))
            newPos.Y = Math.Max(0, Math.Min(newPos.Y, _mapHeight - tile.Size.Height))

            tile.Position = newPos
        Next

        Refresh()
        RaiseEvent CanvasModified()
    End Sub

    Private Sub HandleResizing(currentPoint As Point)
        If selectedTiles.Count = 1 Then
            ResizeSingleTile(currentPoint)
        Else
            ResizeGroupTiles(currentPoint)
        End If
    End Sub

    Private Sub UpdateCursor(currentPoint As Point)
        Dim canvasPoint As Point = ClientToCanvas(currentPoint)

        Dim cursorSet As Boolean = False

        If selectedTiles.Count > 1 Then
            Dim groupDirection As MapTile.ResizeDirections = GetGroupResizeDirection(canvasPoint)
            If groupDirection <> MapTile.ResizeDirections.None Then
                Cursor = GetCursorForDirection(groupDirection)
                cursorSet = True
            End If
        End If

        If Not cursorSet Then
            For Each tile In _tiles
                Dim direction As MapTile.ResizeDirections = GetResizeDirection(tile, canvasPoint)
                If direction <> MapTile.ResizeDirections.None Then
                    Cursor = GetCursorForDirection(direction)
                    cursorSet = True
                    Exit For
                End If
            Next
        End If

        If Not cursorSet Then
            Cursor = Cursors.Default
        End If
    End Sub

    Protected Overrides Sub OnMouseDown(e As MouseEventArgs)
        MyBase.OnMouseDown(e)

        If e.Button = MouseButtons.Left Then
            Dim currentPoint As Point = ClientToCanvas(e.Location)
            Dim clickedTile As MapTile = GetTileAtPoint(currentPoint)

            If IsCtrlKeyPressed Then
                isCtrlClick = True
                mouseDownLocation = e.Location
                ctrlClickTile = clickedTile

                If clickedTile IsNot Nothing Then
                    If selectedTiles.Contains(clickedTile) Then
                        clickedTile.Selected = False
                        Dim unused = selectedTiles.Remove(clickedTile)
                    Else
                        clickedTile.Selected = True
                        selectedTiles.Add(clickedTile)
                    End If

                    Refresh()
                End If
            Else
                ctrlClickTile = Nothing
                HandleLeftMouseDown(e, currentPoint, clickedTile)
                isCtrlClick = False
            End If
        ElseIf e.Button = MouseButtons.Right Then
            Dim currentPoint As Point = e.Location
            isPanning = True
            panStartPoint = currentPoint
            scrollStartPoint = New Point(AutoScrollPosition.X, AutoScrollPosition.Y)
            hasPanned = False
            Cursor = Cursors.Hand
        End If
    End Sub

    Protected Overrides Sub OnMouseMove(e As MouseEventArgs)
        MyBase.OnMouseMove(e)

        Dim currentPoint As Point = e.Location

        If resizing Then
            Dim canvasPoint As Point = ClientToCanvas(currentPoint)
            HandleResizing(canvasPoint)
        ElseIf dragging AndAlso selectedTiles.Count > 0 Then
            Dim canvasPoint As Point = ClientToCanvas(currentPoint)
            HandleDragging(canvasPoint)
        ElseIf isSelecting Then
            Dim canvasPoint As Point = ClientToCanvas(currentPoint)
            selectionEndPoint = canvasPoint
            Refresh()
        ElseIf isPanning AndAlso e.Button = MouseButtons.Right Then
            HandlePanning(currentPoint)
        ElseIf isCtrlClick Then
            If Math.Abs(e.Location.X - mouseDownLocation.X) > DragThreshold OrElse Math.Abs(e.Location.Y - mouseDownLocation.Y) > DragThreshold Then
                If ctrlClickTile IsNot Nothing AndAlso Not selectedTiles.Contains(ctrlClickTile) Then
                    ctrlClickTile.Selected = True
                    selectedTiles.Add(ctrlClickTile)
                End If

                DuplicateSelectedTiles(ClientToCanvas(e.Location))
                dragging = True
                isCtrlClick = False
                ctrlClickTile = Nothing
            End If
        Else
            UpdateCursor(currentPoint)
        End If
    End Sub

    Protected Overrides Sub OnMouseUp(e As MouseEventArgs)
        If e.Button <> MouseButtons.Right Then
            MyBase.OnMouseUp(e)
        End If
        If e.Button = MouseButtons.Right Then
            HandleRightMouseUp(e)
        End If

        If isSelecting Then
            isSelecting = False
            selectionRectangle = GetSelectionRectangle()
            SelectTilesInRectangle(selectionRectangle)
            Refresh()
        End If

        If dragging Then
            If selectedTile IsNot Nothing AndAlso selectedTile.Position <> initialTilePosition AndAlso Not actionAdded Then
                undoRedoManager.AddAction(New MoveTileAction(selectedTile, Me, initialTilePosition, selectedTile.Position))
                actionAdded = True
            End If
            dragging = False
        End If

        If resizing Then
            If selectedTile IsNot Nothing AndAlso selectedTile.Size <> initialTileSize AndAlso Not actionAdded Then
                undoRedoManager.AddAction(New ResizeTileAction(selectedTile, Me, initialTileSize, selectedTile.Size))
                actionAdded = True
            End If
            resizing = False
        End If

        If e.Button = MouseButtons.Left Then
            If isCtrlClick Then
                isCtrlClick = False
                ctrlClickTile = Nothing
            End If
        End If

        If e.Button = MouseButtons.Right Then
            If isPanning Then
                isPanning = False
                Cursor = Cursors.Default
                If hasPanned Then
                    hasPanned = False
                Else
                    HandleRightMouseUp(e)
                End If
            Else
                HandleRightMouseUp(e)
            End If
        End If

        ClearInitialState()
    End Sub
    Private Sub ClearInitialState()
        initialTilePosition = Point.Empty
        initialTileSize = Size.Empty
        selectedTile = Nothing
        actionAdded = False
    End Sub

    Protected Overrides Sub OnCreateControl()
        MyBase.OnCreateControl()
        AllowDrop = True
    End Sub

    Protected Overrides Sub OnDragEnter(drgevent As DragEventArgs)
        MyBase.OnDragEnter(drgevent)
        If drgevent.Data.GetDataPresent(GetType(Bitmap)) Then
            drgevent.Effect = DragDropEffects.Copy
        ElseIf drgevent.Data.GetDataPresent(DataFormats.FileDrop) Then
            drgevent.Effect = DragDropEffects.Copy
        Else
            drgevent.Effect = DragDropEffects.None
        End If
    End Sub

    Protected Overrides Sub OnDragDrop(drgevent As DragEventArgs)
        MyBase.OnDragDrop(drgevent)
        If drgevent.Data.GetDataPresent(GetType(Bitmap)) Then
            Dim image As Image = CType(drgevent.Data.GetData(GetType(Bitmap)), Image)
            Dim imageFilePath As String = Nothing
            If drgevent.Data.GetDataPresent("ImageFilePath") Then
                imageFilePath = CType(drgevent.Data.GetData("ImageFilePath"), String)
            End If
            HandleImageDrop(image, imageFilePath, drgevent)
        ElseIf drgevent.Data.GetDataPresent(DataFormats.FileDrop) Then
            Dim files() As String = CType(drgevent.Data.GetData(DataFormats.FileDrop), String())
            For Each file In files
                If IO.File.Exists(file) Then
                    Try
                        Dim image As Image = Image.FromFile(file)
                        HandleImageDrop(image, file, drgevent)
                    Catch ex As Exception
                    End Try
                End If
            Next
        End If
    End Sub

    Protected Overrides Sub OnMouseEnter(e As EventArgs)
        MyBase.OnMouseEnter(e)
        If Not Focused Then
            Dim unused = Focus()
        End If
    End Sub

    Protected Overrides Sub OnMouseWheel(e As MouseEventArgs)
        Dim unused = Focus()

        Dim mousePosition As Point = e.Location

        If e.Delta > 0 Then
            ZoomIn(mousePosition)
        ElseIf e.Delta < 0 Then
            ZoomOut(mousePosition)
        End If
    End Sub

#End Region

#Region " Helper Methods "

    Private Sub HandleImageDrop(image As Image, imageFilePath As String, drgevent As DragEventArgs)
        Dim isSpriteSheet As Boolean = False
        If drgevent.Data.GetDataPresent("IsSpriteSheet") Then
            isSpriteSheet = CBool(drgevent.Data.GetData("IsSpriteSheet"))
        End If

        Dim frameWidth As Integer = 0
        Dim frameHeight As Integer = 0
        If drgevent.Data.GetDataPresent("FrameWidth") Then
            frameWidth = CInt(drgevent.Data.GetData("FrameWidth"))
        End If
        If drgevent.Data.GetDataPresent("FrameHeight") Then
            frameHeight = CInt(drgevent.Data.GetData("FrameHeight"))
        End If

        Dim spriteSheetImage = If(Not String.IsNullOrEmpty(imageFilePath) AndAlso IO.File.Exists(imageFilePath), Image.FromFile(imageFilePath), image)

        If isSpriteSheet Then
            If frameWidth = 0 Then frameWidth = 32
            If frameHeight = 0 Then frameHeight = 32

            Dim framesInRow As Integer = spriteSheetImage.Width \ frameWidth
            Dim numberOfRows As Integer = spriteSheetImage.Height \ frameHeight

            Dim rowToExtract As Integer = 0

            Dim animationFrames As List(Of Image) = ExtractAnimationFrames(spriteSheetImage, frameWidth, frameHeight, rowToExtract)

            spriteSheetImage.Dispose()

            Dim scaledFrameWidth As Integer = frameWidth * 2
            Dim scaledFrameHeight As Integer = frameHeight * 2

            For i As Integer = 0 To animationFrames.Count - 1
                Dim resizedFrame As New Bitmap(scaledFrameWidth, scaledFrameHeight)
                Using g As Graphics = Graphics.FromImage(resizedFrame)
                    g.InterpolationMode = InterpolationMode.NearestNeighbor
                    g.PixelOffsetMode = PixelOffsetMode.HighQuality
                    g.SmoothingMode = SmoothingMode.None
                    g.DrawImage(animationFrames(i), New Rectangle(0, 0, scaledFrameWidth, scaledFrameHeight))
                End Using
                animationFrames(i).Dispose()
                animationFrames(i) = resizedFrame
            Next

            Dim frameSize As New Size(scaledFrameWidth, scaledFrameHeight)

            Dim point As Point = PointToClient(New Point(drgevent.X, drgevent.Y))
            point = ClientToCanvas(point)

            If snappingEnabled AndAlso Not IsShiftKeyPressed Then
                point.X = CInt(Math.Round(point.X / _gridSize)) * _gridSize
                point.Y = CInt(Math.Round(point.Y / _gridSize)) * _gridSize
            End If

            point.X = Math.Max(0, Math.Min(point.X, _mapWidth - frameSize.Width))
            point.Y = Math.Max(0, Math.Min(point.Y, _mapHeight - frameSize.Height))

            Dim newTile As New MapTile With {
    .AnimationFrames = animationFrames,
    .IsAnimated = True,
    .AnimationInterval = 200,
    .ImageFilePath = imageFilePath,
    .Position = point,
    .Size = frameSize,
    .OriginalSize = frameSize,
    .FrameWidth = frameWidth,
    .FrameHeight = frameHeight
}

            AddTile(newTile)
        Else
            Dim imageClone As Image = CType(image.Clone(), Image)

            Dim originalSize As Size = imageClone.Size

            Dim scaledWidth As Double = originalSize.Width * 0.5
            Dim scaledHeight As Double = originalSize.Height * 0.5

            Dim newWidth As Integer = CInt(Math.Ceiling(scaledWidth / _gridSize)) * _gridSize
            Dim newHeight As Integer = CInt(Math.Ceiling(scaledHeight / _gridSize)) * _gridSize

            newWidth = Math.Min(newWidth, _mapWidth)
            newHeight = Math.Min(newHeight, _mapHeight)

            Dim resizedImage As New Bitmap(newWidth, newHeight, PixelFormat.Format32bppArgb)
            Using g As Graphics = Graphics.FromImage(resizedImage)
                g.InterpolationMode = InterpolationMode.NearestNeighbor
                g.PixelOffsetMode = PixelOffsetMode.Half
                g.SmoothingMode = SmoothingMode.None

                g.Clear(Color.Transparent)
                g.DrawImage(imageClone, New Rectangle(0, 0, newWidth, newHeight))
            End Using

            imageClone.Dispose()

            Dim point As Point = PointToClient(New Point(drgevent.X, drgevent.Y))
            point = ClientToCanvas(point)

            If snappingEnabled AndAlso Not IsShiftKeyPressed Then
                point.X = CInt(point.X / _gridSize) * _gridSize
                point.Y = CInt(point.Y / _gridSize) * _gridSize
            End If

            point.X = Math.Max(0, Math.Min(point.X, _mapWidth - newWidth))
            point.Y = Math.Max(0, Math.Min(point.Y, _mapHeight - newHeight))

            Dim newTile As New MapTile With {
    .Image = resizedImage,
    .ImageFilePath = imageFilePath,
    .Position = point,
    .Size = New Size(newWidth, newHeight),
    .OriginalSize = image.Size
}
            AddTile(newTile)
        End If
    End Sub

    Private Function ExtractBossAnimationFrames(spriteSheet As Image, bossIndex As Integer) As List(Of Image)
        Dim frames As New List(Of Image)

        Dim frameWidth As Integer = 96
        Dim frameHeight As Integer = 96

        Dim framesPerBoss As Integer = 3

        Dim row As Integer = bossIndex
        Dim yOffset As Integer = row * frameHeight

        For col As Integer = 0 To framesPerBoss - 1
            Dim frameRect As New Rectangle(col * frameWidth, yOffset, frameWidth, frameHeight)

            Dim frameImage As New Bitmap(frameWidth, frameHeight)
            Using g As Graphics = Graphics.FromImage(frameImage)
                g.DrawImage(spriteSheet, New Rectangle(0, 0, frameWidth, frameHeight), frameRect, GraphicsUnit.Pixel)
            End Using

            frames.Add(frameImage)
        Next

        Return frames
    End Function

    Private Sub HandlePanning(currentMousePosition As Point)
        hasPanned = True

        Dim deltaX As Integer = currentMousePosition.X - panStartPoint.X
        Dim deltaY As Integer = currentMousePosition.Y - panStartPoint.Y

        Dim newScrollPosition As New Point(scrollStartPoint.X + deltaX, scrollStartPoint.Y + deltaY)

        Dim scaledMapWidth As Integer = _mapWidth * ZoomLevel
        Dim scaledMapHeight As Integer = _mapHeight * ZoomLevel

        Dim maxScrollX As Integer = Math.Max(0, scaledMapWidth - ClientSize.Width)
        Dim maxScrollY As Integer = Math.Max(0, scaledMapHeight - ClientSize.Height)

        Dim offsetX As Integer = 0
        Dim offsetY As Integer = 0

        If scaledMapWidth < ClientSize.Width Then
            offsetX = (ClientSize.Width - scaledMapWidth) \ 2
        End If
        If scaledMapHeight < ClientSize.Height Then
            offsetY = (ClientSize.Height - scaledMapHeight) \ 2
        End If

        Dim minScrollX As Integer = -offsetX
        Dim minScrollY As Integer = -offsetY
        Dim maxScrollXWithOffset As Integer = maxScrollX + offsetX
        Dim maxScrollYWithOffset = maxScrollY + offsetY

        newScrollPosition.X = Math.Max(-maxScrollXWithOffset, Math.Min(-offsetX, newScrollPosition.X))
        newScrollPosition.Y = Math.Max(-maxScrollYWithOffset, Math.Min(-offsetY, newScrollPosition.Y))

        AutoScrollPosition = New Point(-newScrollPosition.X, -newScrollPosition.Y)

        Refresh()
    End Sub

    Public Function ClientToCanvas(point As Point) As Point
        Return New Point((point.X - AutoScrollPosition.X) / ZoomLevel, (point.Y - AutoScrollPosition.Y) / ZoomLevel)
    End Function

    Private Function CanvasToClientRect(rect As Rectangle) As Rectangle
        Dim x As Integer = (rect.X * ZoomLevel) + AutoScrollPosition.X
        Dim y As Integer = (rect.Y * ZoomLevel) + AutoScrollPosition.Y
        Dim width As Integer = rect.Width * ZoomLevel
        Dim height As Integer = rect.Height * ZoomLevel
        Return New Rectangle(x, y, width, height)
    End Function

    Private Sub UpdateScrollBars()
        Dim scaledWidth As Integer = _mapWidth * ZoomLevel
        Dim scaledHeight As Integer = _mapHeight * ZoomLevel

        AutoScrollMinSize = New Size(scaledWidth, scaledHeight)

        Dim offsetX As Integer = 0
        Dim offsetY As Integer = 0

        If scaledWidth < ClientSize.Width Then
            offsetX = (ClientSize.Width - scaledWidth) \ 2
        End If
        If scaledHeight < ClientSize.Height Then
            offsetY = (ClientSize.Height - scaledHeight) \ 2
        End If

        Dim maxScrollX As Integer = Math.Max(0, scaledWidth - ClientSize.Width)
        Dim maxScrollY As Integer = Math.Max(0, scaledHeight - ClientSize.Height)

        Dim minScrollX As Integer = -offsetX
        Dim minScrollY As Integer = -offsetY
        Dim maxScrollXWithOffset As Integer = maxScrollX + offsetX
        Dim maxScrollYWithOffset As Integer = maxScrollY + offsetY

        Dim scrollX As Integer = AutoScrollPosition.X
        Dim scrollY As Integer = AutoScrollPosition.Y

        scrollX = Math.Max(-maxScrollXWithOffset, Math.Min(-offsetX, scrollX))
        scrollY = Math.Max(-maxScrollYWithOffset, Math.Min(-offsetY, scrollY))

        AutoScrollPosition = New Point(scrollX, scrollY)
    End Sub

    Private Sub AdjustScrollPosition(oldZoomLevel As Single, ByVal focusPoint As Point?)
        Dim focus As Point = If(focusPoint, New Point(ClientSize.Width / 2, ClientSize.Height / 2))

        Dim scrollPos As Point = AutoScrollPosition
        Dim offsetX As Integer = 0
        Dim offsetY As Integer = 0

        Dim scaledMapWidth As Integer = _mapWidth * ZoomLevel
        Dim scaledMapHeight As Integer = _mapHeight * ZoomLevel

        If scaledMapWidth < ClientSize.Width Then
            offsetX = (ClientSize.Width - scaledMapWidth) \ 2
        End If
        If scaledMapHeight < ClientSize.Height Then
            offsetY = (ClientSize.Height - scaledMapHeight) \ 2
        End If

        Dim focusX As Single = (-scrollPos.X + focus.X - offsetX) / oldZoomLevel
        Dim focusY As Single = (-scrollPos.Y + focus.Y - offsetY) / oldZoomLevel

        UpdateScrollBars()

        offsetX = 0
        offsetY = 0
        scaledMapWidth = CInt(_mapWidth * ZoomLevel)
        scaledMapHeight = CInt(_mapHeight * ZoomLevel)

        If scaledMapWidth < ClientSize.Width Then
            offsetX = (ClientSize.Width - scaledMapWidth) \ 2
        End If
        If scaledMapHeight < ClientSize.Height Then
            offsetY = (ClientSize.Height - scaledMapHeight) \ 2
        End If

        Dim newScrollX As Integer = -(focusX * ZoomLevel) + focus.X - offsetX
        Dim newScrollY As Integer = -(focusY * ZoomLevel) + focus.Y - offsetY

        Dim maxScrollX As Integer = Math.Max(0, scaledMapWidth - ClientSize.Width)
        Dim maxScrollY As Integer = Math.Max(0, scaledMapHeight - ClientSize.Height)

        Dim minScrollX As Integer = -offsetX
        Dim minScrollY As Integer = -offsetY
        Dim maxScrollXWithOffset As Integer = maxScrollX + offsetX
        Dim maxScrollYWithOffset As Integer = maxScrollY + offsetY

        newScrollX = Math.Max(-maxScrollXWithOffset, Math.Min(-offsetX, newScrollX))
        newScrollY = Math.Max(-maxScrollYWithOffset, Math.Min(-offsetY, newScrollY))

        AutoScrollPosition = New Point(-newScrollX, -newScrollY)
    End Sub

    Private Sub BringTileToFront(tile As MapTile)
        If _tiles.Remove(tile) Then
            _tiles.Add(tile)
            Invalidate()
        End If
    End Sub

    Private Sub SendTileToBack(tile As MapTile)
        If _tiles.Remove(tile) Then
            Dim insertIndex As Integer = _tiles.Count - 1
            For i As Integer = _tiles.Count - 1 To 0 Step -1
                If _tiles(i).IsLocked Then
                    insertIndex = i
                    Exit For
                End If
            Next
            _tiles.Insert(insertIndex, tile)
            AddAction(New MoveTileAction(tile, Me, tile.Position, tile.Position))
            Invalidate()
        End If
    End Sub

    Private Sub DeleteSelectedTiles()
        If selectedTiles.Count > 0 Then
            For Each tile In selectedTiles
                ' Add the remove action to the undo stack
                undoRedoManager.AddAction(New RemoveTileAction(tile, Me))
                ' Remove the tile from the canvas
                RemoveTileInternal(tile)
            Next

            ' Clear the selected tiles list
            selectedTiles.Clear()
            selectedTile = Nothing

            ' Refresh the canvas
            Invalidate()
            RaiseEvent CanvasModified()
        End If
    End Sub

    Private Function GetTileAtPoint(point As Point, Optional includeLockedTiles As Boolean = False) As MapTile
        For i As Integer = _tiles.Count - 1 To 0 Step -1
            Dim tile = _tiles(i)

            If tile.IsLocked AndAlso Not includeLockedTiles Then
                Continue For
            End If

            Dim rect As New Rectangle(tile.Position, tile.Size)
            If rect.Contains(point) Then
                Return tile
            Else
                If IsPointOverTileHandles(tile, point) Then
                    Return tile
                End If
            End If
        Next
        Return Nothing
    End Function

    Private Function IsPointOverTileHandles(tile As MapTile, point As Point) As Boolean
        Dim handleSize As Integer = 6
        Dim adjustedHandleSize As Single = handleSize / ZoomLevel

        Dim rect = New Rectangle(tile.Position, tile.Size)

        Dim topLeftHandle As New RectangleF(rect.Left - (adjustedHandleSize / 2), rect.Top - (adjustedHandleSize / 2), adjustedHandleSize, adjustedHandleSize)
        Dim topRightHandle As New RectangleF(rect.Right - (adjustedHandleSize / 2), rect.Top - (adjustedHandleSize / 2), adjustedHandleSize, adjustedHandleSize)
        Dim bottomLeftHandle As New RectangleF(rect.Left - (adjustedHandleSize / 2), rect.Bottom - (adjustedHandleSize / 2), adjustedHandleSize, adjustedHandleSize)
        Dim bottomRightHandle As New RectangleF(rect.Right - (adjustedHandleSize / 2), rect.Bottom - (adjustedHandleSize / 2), adjustedHandleSize, adjustedHandleSize)

        Return topLeftHandle.Contains(point) OrElse topRightHandle.Contains(point) OrElse bottomLeftHandle.Contains(point) OrElse bottomRightHandle.Contains(point)
    End Function

    Private Function GetResizeDirection(tile As MapTile, canvasPoint As Point) As MapTile.ResizeDirections
        Dim handleSize As Integer = 6

        Dim adjustedHandleSize As Single = handleSize / ZoomLevel

        Dim rect = New Rectangle(tile.Position, tile.Size)
        Dim direction As MapTile.ResizeDirections = MapTile.ResizeDirections.None

        Dim topLeftHandle As New RectangleF(rect.Left - (adjustedHandleSize / 2), rect.Top - (adjustedHandleSize / 2), adjustedHandleSize, adjustedHandleSize)
        Dim topRightHandle As New RectangleF(rect.Right - (adjustedHandleSize / 2), rect.Top - (adjustedHandleSize / 2), adjustedHandleSize, adjustedHandleSize)
        Dim bottomLeftHandle As New RectangleF(rect.Left - (adjustedHandleSize / 2), rect.Bottom - (adjustedHandleSize / 2), adjustedHandleSize, adjustedHandleSize)
        Dim bottomRightHandle As New RectangleF(rect.Right - (adjustedHandleSize / 2), rect.Bottom - (adjustedHandleSize / 2), adjustedHandleSize, adjustedHandleSize)

        If topLeftHandle.Contains(canvasPoint) Then
            direction = MapTile.ResizeDirections.Left Or MapTile.ResizeDirections.Top
        ElseIf topRightHandle.Contains(canvasPoint) Then
            direction = MapTile.ResizeDirections.Right Or MapTile.ResizeDirections.Top
        ElseIf bottomLeftHandle.Contains(canvasPoint) Then
            direction = MapTile.ResizeDirections.Left Or MapTile.ResizeDirections.Bottom
        ElseIf bottomRightHandle.Contains(canvasPoint) Then
            direction = MapTile.ResizeDirections.Right Or MapTile.ResizeDirections.Bottom
        End If

        Return direction
    End Function

    Private Function GetGroupResizeDirection(canvasPoint As Point) As MapTile.ResizeDirections
        If selectedTiles.Count <= 1 Then Return MapTile.ResizeDirections.None

        Dim handleSize As Integer = 6

        Dim adjustedHandleSize As Single = handleSize / ZoomLevel

        Dim bounds = GetSelectedTilesBounds()

        Dim direction As MapTile.ResizeDirections = MapTile.ResizeDirections.None

        Dim topLeftHandle As New RectangleF(bounds.Left - (adjustedHandleSize / 2), bounds.Top - (adjustedHandleSize / 2), adjustedHandleSize, adjustedHandleSize)
        Dim topRightHandle As New RectangleF(bounds.Right - (adjustedHandleSize / 2), bounds.Top - (adjustedHandleSize / 2), adjustedHandleSize, adjustedHandleSize)
        Dim bottomLeftHandle As New RectangleF(bounds.Left - (adjustedHandleSize / 2), bounds.Bottom - (adjustedHandleSize / 2), adjustedHandleSize, adjustedHandleSize)
        Dim bottomRightHandle As New RectangleF(bounds.Right - (adjustedHandleSize / 2), bounds.Bottom - (adjustedHandleSize / 2), adjustedHandleSize, adjustedHandleSize)

        If topLeftHandle.Contains(canvasPoint) Then
            direction = MapTile.ResizeDirections.Left Or MapTile.ResizeDirections.Top
        ElseIf topRightHandle.Contains(canvasPoint) Then
            direction = MapTile.ResizeDirections.Right Or MapTile.ResizeDirections.Top
        ElseIf bottomLeftHandle.Contains(canvasPoint) Then
            direction = MapTile.ResizeDirections.Left Or MapTile.ResizeDirections.Bottom
        ElseIf bottomRightHandle.Contains(canvasPoint) Then
            direction = MapTile.ResizeDirections.Right Or MapTile.ResizeDirections.Bottom
        End If

        Return direction
    End Function

    Private Function GetSelectedTilesBounds() As Rectangle
        If selectedTiles.Count = 0 Then Return Rectangle.Empty

        Dim minX As Integer = Integer.MaxValue
        Dim minY As Integer = Integer.MaxValue
        Dim maxX As Integer = Integer.MinValue
        Dim maxY As Integer = Integer.MinValue

        For Each tile In selectedTiles
            minX = Math.Min(minX, tile.Position.X)
            minY = Math.Min(minY, tile.Position.Y)
            maxX = Math.Max(maxX, tile.Position.X + tile.Size.Width)
            maxY = Math.Max(maxY, tile.Position.Y + tile.Size.Height)
        Next

        Return New Rectangle(minX, minY, maxX - minX, maxY - minY)
    End Function

    Private Function GetCursorForDirection(direction As MapTile.ResizeDirections) As Cursor
        Select Case direction
            Case MapTile.ResizeDirections.Left Or MapTile.ResizeDirections.Top,
                 MapTile.ResizeDirections.Right Or MapTile.ResizeDirections.Bottom
                Return Cursors.SizeNWSE
            Case MapTile.ResizeDirections.Right Or MapTile.ResizeDirections.Top,
                 MapTile.ResizeDirections.Left Or MapTile.ResizeDirections.Bottom
                Return Cursors.SizeNESW
            Case MapTile.ResizeDirections.Left, MapTile.ResizeDirections.Right
                Return Cursors.SizeWE
            Case MapTile.ResizeDirections.Top, MapTile.ResizeDirections.Bottom
                Return Cursors.SizeNS
            Case Else
                Return Cursors.Default
        End Select
    End Function

    Private Function GetSelectionRectangle() As Rectangle
        Dim x As Integer = Math.Min(selectionStartPoint.X, selectionEndPoint.X)
        Dim y As Integer = Math.Min(selectionStartPoint.Y, selectionEndPoint.Y)
        Dim width As Integer = Math.Abs(selectionStartPoint.X - selectionEndPoint.X)
        Dim height As Integer = Math.Abs(selectionStartPoint.Y - selectionEndPoint.Y)
        Return New Rectangle(x, y, width, height)
    End Function

    Private Sub SelectTilesInRectangle(rect As Rectangle)
        selectedTiles.Clear()
        For Each tile In _tiles
            If tile.IsLocked Then
                tile.Selected = False
                Continue For
            End If
            If rect.IntersectsWith(New Rectangle(tile.Position, tile.Size)) Then
                tile.Selected = True
                selectedTiles.Add(tile)
            Else
                tile.Selected = False
            End If
        Next
    End Sub

    Private Sub DeselectAllTiles()
        For Each tile In _tiles
            tile.Selected = False
            tile.CurrentResizeDirection = MapTile.ResizeDirections.None
        Next
        selectedTiles.Clear()
    End Sub

    Public Sub SetMapSize(width As Integer, height As Integer)
        _mapWidth = width
        _mapHeight = height

        For Each tile In _tiles
            Dim newX As Integer = Math.Max(0, Math.Min(tile.Position.X, _mapWidth - tile.Size.Width))
            Dim newY As Integer = Math.Max(0, Math.Min(tile.Position.Y, _mapHeight - tile.Size.Height))
            tile.Position = New Point(newX, newY)

            If tile.Position.X + tile.Size.Width > _mapWidth Then
                tile.Size = New Size(_mapWidth - tile.Position.X, tile.Size.Height)
            End If
            If tile.Position.Y + tile.Size.Height > _mapHeight Then
                tile.Size = New Size(tile.Size.Width, _mapHeight - tile.Position.Y)
            End If

            If tile.Size.Width < 1 Then tile.Size = New Size(1, tile.Size.Height)
            If tile.Size.Height < 1 Then tile.Size = New Size(tile.Size.Width, 1)
        Next

        UpdateScrollBars()
        Invalidate()
    End Sub

    Public Sub SnapAllTilesToGrid()
        For Each tile In _tiles
            tile.Position = New Point(CInt(tile.Position.X / _gridSize) * _gridSize,
                                      CInt(tile.Position.Y / _gridSize) * _gridSize)
            tile.Size = New Size(CInt(tile.Size.Width / _gridSize) * _gridSize,
                                 CInt(tile.Size.Height / _gridSize) * _gridSize)
        Next
        Invalidate()
    End Sub

    Private ReadOnly Property IsShiftKeyPressed As Boolean
        Get
            Return (ModifierKeys And Keys.Shift) = Keys.Shift
        End Get
    End Property

    Private ReadOnly Property IsCtrlKeyPressed As Boolean
        Get
            Return (Control.ModifierKeys And Keys.Control) = Keys.Control
        End Get
    End Property

    Private Function GetVisibleCanvasRectangle() As Rectangle
        Dim left As Integer = -AutoScrollPosition.X / ZoomLevel
        Dim top As Integer = -AutoScrollPosition.Y / ZoomLevel
        Dim width As Integer = ClientSize.Width / ZoomLevel
        Dim height As Integer = ClientSize.Height / ZoomLevel
        Return New Rectangle(left, top, width, height)
    End Function

#End Region

#Region " Zoom Methods "

    Private Sub ZoomIn(ByVal focusPoint As Point?)
        ZoomLevel *= 1.1F
    End Sub

    Private Sub ZoomOut(ByVal focusPoint As Point?)
        ZoomLevel /= 1.1F
    End Sub

    Public Sub ZoomToFit()
        Dim zoomX As Single = ClientSize.Width / _mapWidth
        Dim zoomY As Single = ClientSize.Height / _mapHeight

        Dim newZoomLevel As Single = Math.Min(zoomX, zoomY)

        If newZoomLevel <= 0 Then
            newZoomLevel = 0.01F
        End If

        Dim oldZoomLevel As Single = _zoomLevel
        _zoomLevel = newZoomLevel
        AdjustScrollPosition(oldZoomLevel, New Point(ClientSize.Width / 2, ClientSize.Height / 2))
        UpdateScrollBars()
        Invalidate()
        RaiseEvent ZoomLevelChanged(_zoomLevel)
    End Sub

#End Region

#Region " CTMMenu "
    Private Sub CTMMenu_Opening(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles CTMMenu.Opening
        If selectedTiles.Count > 0 Then
            ' Enable/disable the Ungroup menu item based on whether the selected tile is grouped
            MnuUnGroup.Enabled = selectedTiles.Count = 1 AndAlso selectedTiles(0).IsGrouped
        Else
            ' If no tiles are selected, disable the Ungroup menu item
            MnuUnGroup.Enabled = False
        End If
    End Sub
    Private Sub MnuFlipHorizontal_Click(sender As Object, e As EventArgs) Handles MnuFlipHorizontal.Click
        If selectedTiles.Count > 0 Then
            FlipSelectedTiles(RotateFlipType.RotateNoneFlipX)
        ElseIf contextMenuTile IsNot Nothing Then
            FlipTile(contextMenuTile, RotateFlipType.RotateNoneFlipX)
        End If
        contextMenuTile = Nothing
        Refresh()
        RaiseEvent CanvasModified()
    End Sub

    Private Sub MnuFlipVertical_Click(sender As Object, e As EventArgs) Handles MnuFlipVertical.Click
        If selectedTiles.Count > 0 Then
            FlipSelectedTiles(RotateFlipType.RotateNoneFlipY)
        ElseIf contextMenuTile IsNot Nothing Then
            FlipTile(contextMenuTile, RotateFlipType.RotateNoneFlipY)
        End If
        contextMenuTile = Nothing
        Refresh()
        RaiseEvent CanvasModified()
    End Sub

    Private Sub FlipSelectedTiles(flipType As RotateFlipType)
        For Each tile In selectedTiles
            FlipTile(tile, flipType)
        Next
    End Sub

    Private Sub FlipTile(tile As MapTile, flipType As RotateFlipType)
        If tile.IsAnimated AndAlso tile.AnimationFrames IsNot Nothing Then
            For i As Integer = 0 To tile.AnimationFrames.Count - 1
                tile.AnimationFrames(i).RotateFlip(flipType)
            Next
        ElseIf tile.Image IsNot Nothing Then
            tile.Image.RotateFlip(flipType)
        End If

        Select Case flipType
            Case RotateFlipType.RotateNoneFlipX
                tile.IsFlippedHorizontally = Not tile.IsFlippedHorizontally
            Case RotateFlipType.RotateNoneFlipY
                tile.IsFlippedVertically = Not tile.IsFlippedVertically
            Case RotateFlipType.RotateNoneFlipXY
                tile.IsFlippedHorizontally = Not tile.IsFlippedHorizontally
                tile.IsFlippedVertically = Not tile.IsFlippedVertically
            Case Else
        End Select
    End Sub

    Private Sub MnuLock_Click(sender As Object, e As EventArgs) Handles MnuLock.Click
        If selectedTiles.Count > 0 Then
            For Each tile In selectedTiles
                tile.IsLocked = True
                tile.Selected = False
            Next
            selectedTiles.Clear()
        ElseIf contextMenuTile IsNot Nothing Then
            contextMenuTile.IsLocked = True
        End If
        contextMenuTile = Nothing
        Refresh()
    End Sub

    Private Sub MnuUnlock_Click(sender As Object, e As EventArgs) Handles MnuUnlock.Click
        If selectedTiles.Count > 0 Then
            For Each tile In selectedTiles
                tile.IsLocked = False
            Next
            Refresh()
        ElseIf contextMenuTile IsNot Nothing Then
            contextMenuTile.IsLocked = False
            Refresh()
        Else
            Dim unused = MessageBox.Show("No tile selected to unlock.", "Unlock Tile", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
        contextMenuTile = Nothing
        RaiseEvent CanvasModified()
    End Sub

    Private Sub Mnu100_Click(sender As Object, e As EventArgs) Handles Mnu100.Click
        If selectedTiles.Count > 0 Then
            ResizeSelectedTilesToPercentage(100)
        End If
    End Sub

    Private Sub Mnu50_Click(sender As Object, e As EventArgs) Handles Mnu50.Click
        If selectedTiles.Count > 0 Then
            ResizeSelectedTilesToPercentage(50)
        End If
    End Sub

    Private Sub Mnu25_Click(sender As Object, e As EventArgs) Handles Mnu25.Click
        If selectedTiles.Count > 0 Then
            ResizeSelectedTilesToPercentage(25)
        End If
    End Sub

    Private Sub ResizeSelectedTilesToPercentage(percentage As Integer)
        For Each tile In selectedTiles
            Dim originalSize As Size = tile.OriginalSize

            Dim newWidth As Integer = originalSize.Width * percentage / 100
            Dim newHeight As Integer = originalSize.Height * percentage / 100

            If snappingEnabled AndAlso Not IsShiftKeyPressed Then
                newWidth = CInt(Math.Ceiling(newWidth / _gridSize)) * _gridSize
                newHeight = CInt(Math.Ceiling(newHeight / _gridSize)) * _gridSize
            End If

            If newWidth <= 1 Then newWidth = 1
            If newHeight <= 1 Then newHeight = 1

            tile.Size = New Size(newWidth, newHeight)
            Dim newPosition As Point = tile.Position

            If newPosition.X + newWidth > _mapWidth Then
                newPosition.X = _mapWidth - newWidth
                If newPosition.X < 0 Then
                    newPosition.X = 0
                    newWidth = _mapWidth
                End If
            End If

            If newPosition.Y + newHeight > _mapHeight Then
                newPosition.Y = _mapHeight - newHeight
                If newPosition.Y < 0 Then
                    newPosition.Y = 0
                    newHeight = _mapHeight
                End If
            End If

            tile.Position = newPosition
            tile.Size = New Size(newWidth, newHeight)

            RaiseEvent TileSizeChanged(tile)
        Next
        Refresh()
        RaiseEvent CanvasModified()
    End Sub

    Private Sub MnuSendToBack_Click(sender As Object, e As EventArgs) Handles MnuSendToBack.Click
        If selectedTiles.Count > 0 Then
            For Each tile In selectedTiles
                Dim oldPosition = tile.Position
                SendTileToBack(tile)
                AddAction(New MoveTileAction(tile, PicCanvas, oldPosition, tile.Position))
            Next
            Refresh()
        End If
    End Sub

    Private Sub MnuBringToFront_Click(sender As Object, e As EventArgs) Handles MnuBringToFront.Click
        If selectedTiles.Count > 0 Then
            For Each tile In selectedTiles
                BringTileToFront(tile)
            Next
            Refresh()
        End If
    End Sub

    Private Sub MnuDelete_Click(sender As Object, e As EventArgs) Handles MnuDelete.Click
        If selectedTiles.Count > 0 Then
            For Each tile In selectedTiles
                AddAction(New RemoveTileAction(tile, PicCanvas))
            Next
            DeleteSelectedTiles()
        End If
    End Sub

    Private Sub MnuRotate90_Click(sender As Object, e As EventArgs) Handles MnuRotate90.Click
        If selectedTiles.Count > 0 Then
            RotateSelectedTiles(90)
        ElseIf contextMenuTile IsNot Nothing Then
            RotateTile(contextMenuTile, 90)
        End If
        contextMenuTile = Nothing
        Refresh()
        RaiseEvent CanvasModified()
    End Sub

    Private Sub MnuRotate180_Click(sender As Object, e As EventArgs) Handles MnuRotate180.Click
        If selectedTiles.Count > 0 Then
            RotateSelectedTiles(180)
        ElseIf contextMenuTile IsNot Nothing Then
            RotateTile(contextMenuTile, 180)
        End If
        contextMenuTile = Nothing
        Refresh()
        RaiseEvent CanvasModified()
    End Sub

    Private Sub MnuRotate270_Click(sender As Object, e As EventArgs) Handles MnuRotate270.Click
        If selectedTiles.Count > 0 Then
            RotateSelectedTiles(270)
        ElseIf contextMenuTile IsNot Nothing Then
            RotateTile(contextMenuTile, 270)
        End If
        contextMenuTile = Nothing
        Refresh()
        RaiseEvent CanvasModified()
    End Sub


#End Region

#Region " Group "
    Private Sub MnuGroup_Click(sender As Object, e As EventArgs) Handles MnuGroup.Click
        If selectedTiles.Count > 1 Then
            GroupSelectedTiles()
            Refresh()
        Else
            Dim unused = MessageBox.Show("Please select at least two tiles to group.", "Group Tiles", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub
    Private Sub MnuUngroup_Click(sender As Object, e As EventArgs) Handles MnuUnGroup.Click
        If selectedTiles.Count = 1 AndAlso selectedTiles(0).IsGrouped Then
            UngroupTile(selectedTiles(0))
        Else
            MessageBox.Show("Please select a grouped tile to ungroup.", "Ungroup Tiles", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub
    Private Sub UngroupTile(groupedTile As MapTile)
        If Not groupedTile.IsGrouped Then Return

        ' Remove the grouped tile from the canvas
        PicCanvas.RemoveTile(groupedTile)

        ' Add the original tiles back to the canvas
        For Each originalTile In groupedTile.OriginalTiles
            PicCanvas.AddTile(originalTile)
        Next

        ' Clear the selected tiles list and select the original tiles
        selectedTiles.Clear()
        For Each originalTile In groupedTile.OriginalTiles
            originalTile.Selected = True
            selectedTiles.Add(originalTile)
        Next

        ' Refresh the canvas
        Refresh()
        RaiseEvent CanvasModified()
    End Sub
    Private Sub GroupSelectedTiles()
        ' Check if any of the selected tiles are animated
        For Each tile In selectedTiles
            If tile.IsAnimated Then
                MessageBox.Show("Animated tiles cannot be grouped.", "Grouping Not Allowed", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Return
            End If
        Next

        ' Get the bounds of the selected tiles
        Dim bounds As Rectangle = GetSelectedTilesBounds()

        ' Create a new bitmap for the merged image
        Dim mergedImage As New Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb)
        Dim selectedTilesInOrder As New List(Of MapTile) ' Declare selectedTilesInOrder here
        Using g As Graphics = Graphics.FromImage(mergedImage)
            g.InterpolationMode = InterpolationMode.NearestNeighbor
            g.PixelOffsetMode = PixelOffsetMode.Half
            g.SmoothingMode = SmoothingMode.None

            g.Clear(Color.Transparent)

            ' Populate selectedTilesInOrder with the currently selected tiles
            For Each tile In selectedTiles
                selectedTilesInOrder.Add(tile)
            Next

            ' Draw each tile onto the merged image
            For Each tile In selectedTilesInOrder
                Dim offsetX As Integer = tile.Position.X - bounds.X
                Dim offsetY As Integer = tile.Position.Y - bounds.Y

                g.DrawImage(tile.Image, New Rectangle(offsetX, offsetY, tile.Size.Width, tile.Size.Height))
            Next
        End Using

        ' Create a new grouped tile
        Dim newTile As New MapTile With {
            .Image = mergedImage,
            .Position = New Point(bounds.X, bounds.Y),
            .Size = mergedImage.Size,
            .Selected = True,
            .IsGrouped = True,
            .OriginalTiles = selectedTilesInOrder ' Now it's accessible here
        }

        ' Remove the original tiles from the canvas
        _tiles.RemoveAll(Function(t) t.Selected)

        ' Add the new grouped tile to the canvas
        _tiles.Add(newTile)

        ' Clear the selected tiles list and select the new grouped tile
        selectedTiles.Clear()
        selectedTiles.Add(newTile)
        selectedTile = newTile

        ' Notify that the canvas has been modified
        RaiseEvent CanvasModified()
    End Sub
#End Region

#Region " Tile Manipulation Methods "

    Private Sub RotateSelectedTiles(angle As Single)
        For Each tile In selectedTiles
            RotateTile(tile, angle)
        Next
    End Sub

    Private Sub RotateTile(tile As MapTile, angle As Integer)
        Dim rotateFlipType As RotateFlipType
        Select Case angle Mod 360
            Case 90
                rotateFlipType = RotateFlipType.Rotate90FlipNone
            Case 180
                rotateFlipType = RotateFlipType.Rotate180FlipNone
            Case 270
                rotateFlipType = RotateFlipType.Rotate270FlipNone
            Case Else
                Return
        End Select

        If tile.IsAnimated AndAlso tile.AnimationFrames IsNot Nothing Then
            For i As Integer = 0 To tile.AnimationFrames.Count - 1
                tile.AnimationFrames(i).RotateFlip(rotateFlipType)
            Next
            If angle Mod 180 <> 0 Then
                tile.Size = New Size(tile.Size.Height, tile.Size.Width)
            End If
        ElseIf tile.Image IsNot Nothing Then
            tile.Image.RotateFlip(rotateFlipType)
            If angle Mod 180 <> 0 Then
                tile.Size = New Size(tile.Size.Height, tile.Size.Width)
            End If
        End If

        tile.RotationAngle = (tile.RotationAngle + angle) Mod 360

        Dim oldCenter As New Point(tile.Position.X + (tile.Size.Width \ 2), tile.Position.Y + (tile.Size.Height \ 2))
        tile.Position = New Point(oldCenter.X - (tile.Size.Width \ 2), oldCenter.Y - (tile.Size.Height \ 2))

        If snappingEnabled AndAlso Not IsShiftKeyPressed Then
            tile.Position = New Point(CInt(Math.Round(tile.Position.X / _gridSize)) * _gridSize,
                                  CInt(Math.Round(tile.Position.Y / _gridSize)) * _gridSize)
        End If
    End Sub

    Private Function RotateImage(img As Image, angle As Single) As Image
        ArgumentNullException.ThrowIfNull(img)

        Dim rotatedBmp As New Bitmap(img.Height, img.Width)
        rotatedBmp.SetResolution(img.HorizontalResolution, img.VerticalResolution)

        Using g As Graphics = Graphics.FromImage(rotatedBmp)
            g.TranslateTransform(rotatedBmp.Width / 2, rotatedBmp.Height / 2)
            g.RotateTransform(angle)
            g.TranslateTransform(-img.Width / 2, -img.Height / 2)
            g.DrawImage(img, New Point(0, 0))
        End Using

        Return rotatedBmp
    End Function

    Private Sub HandleTileClick(e As MouseEventArgs, currentPoint As Point, clickedTile As MapTile)
        If clickedTile IsNot Nothing AndAlso Not clickedTile.IsLocked Then
            If selectedTiles.Contains(clickedTile) Then
                For Each tile In selectedTiles
                    tile.InitialPosition = tile.Position
                Next
                initialMousePosition = currentPoint
                dragging = True
                Refresh()
            Else
                DeselectAllTiles()
                selectedTile = clickedTile
                selectedTile.Selected = True
                selectedTiles.Clear()
                selectedTiles.Add(selectedTile)

                selectedTile.InitialPosition = selectedTile.Position
                initialMousePosition = currentPoint
                dragging = True
                Refresh()
            End If
        Else
            StartSelection(currentPoint)
        End If
    End Sub

    Private Sub DuplicateSelectedTiles(currentPoint As Point)
        Dim duplicates As New List(Of MapTile)

        For Each tile In selectedTiles
            Dim duplicateTile As MapTile = tile.Clone()
            _tiles.Add(duplicateTile)
            duplicates.Add(duplicateTile)
        Next

        For Each tile In _tiles
            tile.Selected = False
        Next

        selectedTiles = duplicates
        For Each tile In selectedTiles
            tile.Selected = True
            tile.InitialPosition = tile.Position
        Next

        initialMousePosition = currentPoint

        dragging = True
        Refresh()
        RaiseEvent CanvasModified()

        For Each tile In duplicates
            undoRedoManager.AddAction(New AddTileAction(tile, Me))
        Next
    End Sub

    Private Sub StartSelection(currentPoint As Point)
        isSelecting = True
        selectionStartPoint = currentPoint
        selectionEndPoint = currentPoint
        DeselectAllTiles()
        Refresh()
    End Sub

    Private Sub StartGroupResizing(currentPoint As Point, groupDirection As MapTile.ResizeDirections)
        resizing = True
        initialMousePosition = currentPoint

        initialSelectedTilesBounds = GetSelectedTilesBounds()
        initialSelectedTilesPositionsAndSizes = New List(Of Tuple(Of MapTile, Point, Size))
        For Each tile In selectedTiles
            initialSelectedTilesPositionsAndSizes.Add(Tuple.Create(tile, tile.Position, tile.Size))
        Next

        For Each tile In selectedTiles
            tile.CurrentResizeDirection = groupDirection
        Next

        Refresh()
    End Sub

    Private Sub StartSingleTileResizing(clickedTile As MapTile, currentPoint As Point, direction As MapTile.ResizeDirections)
        DeselectAllTiles()
        selectedTile = clickedTile
        selectedTile.Selected = True
        selectedTiles.Clear()
        selectedTiles.Add(selectedTile)

        resizing = True
        selectedTile.IsResizing = True
        selectedTile.CurrentResizeDirection = direction

        initialTilePosition = selectedTile.Position
        initialTileSize = selectedTile.Size
        initialMousePosition = currentPoint
        Refresh()
    End Sub

    Private Sub DuplicateTile(clickedTile As MapTile, currentPoint As Point)
        Dim duplicateTile As MapTile = clickedTile.Clone()
        _tiles.Add(duplicateTile)
        DeselectAllTiles()
        selectedTile = duplicateTile
        selectedTile.Selected = True
        selectedTiles.Clear()
        selectedTiles.Add(selectedTile)

        initialTilePosition = duplicateTile.Position
        duplicateTile.InitialPosition = duplicateTile.Position
        initialMousePosition = currentPoint

        dragging = True
        Refresh()
    End Sub

    Private Sub ResizeSingleTile(currentPoint As Point)
        Dim deltaX As Integer = currentPoint.X - initialMousePosition.X
        Dim deltaY As Integer = currentPoint.Y - initialMousePosition.Y

        Dim newSize As Size = initialTileSize
        Dim newPosition As Point = initialTilePosition

        If selectedTile.CurrentResizeDirection.HasFlag(MapTile.ResizeDirections.Right) Then
            newSize.Width = initialTileSize.Width + deltaX
        End If
        If selectedTile.CurrentResizeDirection.HasFlag(MapTile.ResizeDirections.Bottom) Then
            newSize.Height = initialTileSize.Height + deltaY
        End If
        If selectedTile.CurrentResizeDirection.HasFlag(MapTile.ResizeDirections.Left) Then
            newSize.Width = initialTileSize.Width - deltaX
            newPosition.X = initialTilePosition.X + deltaX
        End If
        If selectedTile.CurrentResizeDirection.HasFlag(MapTile.ResizeDirections.Top) Then
            newSize.Height = initialTileSize.Height - deltaY
            newPosition.Y = initialTilePosition.Y + deltaY
        End If

        If newSize.Width <= 1 Then newSize.Width = 1
        If newSize.Height <= 1 Then newSize.Height = 1

        If snappingEnabled AndAlso Not IsShiftKeyPressed Then
            newSize.Width = CInt(Math.Ceiling(newSize.Width / _gridSize)) * _gridSize
            newSize.Height = CInt(Math.Ceiling(newSize.Height / _gridSize)) * _gridSize
            newPosition.X = CInt(Math.Round(newPosition.X / _gridSize)) * _gridSize
            newPosition.Y = CInt(Math.Round(newPosition.Y / _gridSize)) * _gridSize
        End If

        If newPosition.X < 0 Then
            newSize.Width += newPosition.X
            newPosition.X = 0
        End If
        If newPosition.Y < 0 Then
            newSize.Height += newPosition.Y
            newPosition.Y = 0
        End If
        If newPosition.X + newSize.Width > _mapWidth Then
            newSize.Width = _mapWidth - newPosition.X
        End If
        If newPosition.Y + newSize.Height > _mapHeight Then
            newSize.Height = _mapHeight - newPosition.Y
        End If

        If newSize.Width <= 1 Then newSize.Width = 1
        If newSize.Height <= 1 Then newSize.Height = 1

        selectedTile.Size = newSize
        selectedTile.Position = newPosition

        RaiseEvent TileSizeChanged(selectedTile)

        Refresh()
        RaiseEvent CanvasModified()
    End Sub

    Private Sub ResizeGroupTiles(currentPoint As Point)
        Dim deltaX As Integer = currentPoint.X - initialMousePosition.X
        Dim deltaY As Integer = currentPoint.Y - initialMousePosition.Y

        Dim newBounds As Rectangle = initialSelectedTilesBounds

        Dim resizeDirection = selectedTiles(0).CurrentResizeDirection

        If resizeDirection.HasFlag(MapTile.ResizeDirections.Right) Then
            newBounds.Width = initialSelectedTilesBounds.Width + deltaX
        End If
        If resizeDirection.HasFlag(MapTile.ResizeDirections.Bottom) Then
            newBounds.Height = initialSelectedTilesBounds.Height + deltaY
        End If
        If resizeDirection.HasFlag(MapTile.ResizeDirections.Left) Then
            newBounds.Width = initialSelectedTilesBounds.Width - deltaX
            newBounds.X = initialSelectedTilesBounds.X + deltaX
        End If
        If resizeDirection.HasFlag(MapTile.ResizeDirections.Top) Then
            newBounds.Height = initialSelectedTilesBounds.Height - deltaY
            newBounds.Y = initialSelectedTilesBounds.Y + deltaY
        End If

        If newBounds.Width <= 1 Then newBounds.Width = 1
        If newBounds.Height <= 1 Then newBounds.Height = 1

        If newBounds.X < 0 Then
            newBounds.Width += newBounds.X
            newBounds.X = 0
        End If
        If newBounds.Y < 0 Then
            newBounds.Height += newBounds.Y
            newBounds.Y = 0
        End If
        If newBounds.X + newBounds.Width > _mapWidth Then
            newBounds.Width = _mapWidth - newBounds.X
        End If
        If newBounds.Y + newBounds.Height > _mapHeight Then
            newBounds.Height = _mapHeight - newBounds.Y
        End If

        If newBounds.Width <= 1 Then newBounds.Width = 1
        If newBounds.Height <= 1 Then newBounds.Height = 1

        Dim scaleX As Double = newBounds.Width / initialSelectedTilesBounds.Width
        Dim scaleY As Double = newBounds.Height / initialSelectedTilesBounds.Height

        For Each item In initialSelectedTilesPositionsAndSizes
            Dim tile = item.Item1
            Dim initialPos = item.Item2
            Dim initialSize = item.Item3

            Dim relX As Double = (initialPos.X - initialSelectedTilesBounds.X) / initialSelectedTilesBounds.Width
            Dim relY As Double = (initialPos.Y - initialSelectedTilesBounds.Y) / initialSelectedTilesBounds.Height

            Dim newPosX As Double = newBounds.X + (relX * newBounds.Width)
            Dim newPosY As Double = newBounds.Y + (relY * newBounds.Height)

            Dim newWidth As Double = initialSize.Width * scaleX
            Dim newHeight As Double = initialSize.Height * scaleY

            If newWidth <= 1 Then newWidth = 1
            If newHeight <= 1 Then newHeight = 1

            If snappingEnabled AndAlso Not IsShiftKeyPressed Then
                newPosX = CInt(Math.Round(newPosX / _gridSize)) * _gridSize
                newPosY = CInt(Math.Round(newPosY / _gridSize)) * _gridSize
                newWidth = CInt(Math.Ceiling(newWidth / _gridSize)) * _gridSize
                newHeight = CInt(Math.Ceiling(newHeight / _gridSize)) * _gridSize
            End If

            newPosX = Math.Max(0, Math.Min(newPosX, _mapWidth - newWidth))
            newPosY = Math.Max(0, Math.Min(newPosY, _mapHeight - newHeight))
            newWidth = Math.Min(newWidth, _mapWidth - newPosX)
            newHeight = Math.Min(newHeight, _mapHeight - newPosY)

            tile.Position = New Point(newPosX, newPosY)
            tile.Size = New Size(newWidth, newHeight)
        Next

        Refresh()
        RaiseEvent CanvasModified()
    End Sub

    Private Sub HandleDragDrop(drgevent As DragEventArgs)
        Dim image As Image = CType(drgevent.Data.GetData("ImageFormat"), Image)
        Dim imageFilePath As String = CType(drgevent.Data.GetData("ImageFilePath"), String)

        Dim originalSize As Size = image.Size

        Dim newWidth As Integer = CInt(originalSize.Width / _gridSize) * _gridSize
        Dim newHeight As Integer = CInt(originalSize.Height / _gridSize) * _gridSize

        If newWidth < _gridSize Then newWidth = _gridSize
        If newHeight < _gridSize Then newHeight = _gridSize

        Dim resizedImage As New Bitmap(image, New Size(newWidth, newHeight))

        Dim point As Point = PointToClient(New Point(drgevent.X, drgevent.Y))
        point = ClientToCanvas(point)

        If snappingEnabled AndAlso Not IsShiftKeyPressed Then
            point.X = CInt(point.X / _gridSize) * _gridSize
            point.Y = CInt(point.Y / _gridSize) * _gridSize
        End If

        Dim newTile As New MapTile With {
            .Image = resizedImage,
            .ImageFilePath = imageFilePath,
            .Position = point,
            .Size = resizedImage.Size
        }
        AddTile(newTile)
    End Sub

    Public Sub ClearTiles()
        _tiles.Clear()
        Invalidate()
    End Sub
#End Region

#Region " Timers "

    Private Sub AnimationTimer_Tick(sender As Object, e As EventArgs)
        Invalidate()
    End Sub

    Private Sub MapCanvas_Disposed(sender As Object, e As EventArgs) Handles Me.Disposed
        If animationTimer IsNot Nothing Then
            animationTimer.Stop()
            animationTimer.Dispose()
            animationTimer = Nothing
        End If

        If _tiles IsNot Nothing Then
            For Each tile In _tiles
                tile.Dispose()
            Next
            _tiles.Clear()
            _tiles = Nothing
        End If
    End Sub

#End Region

#Region " Key Down "

    Protected Overrides Sub OnKeyDown(e As KeyEventArgs)
        MyBase.OnKeyDown(e)

        If e.Control AndAlso e.KeyCode = Keys.Z Then
            Undo()
            e.Handled = True
        ElseIf e.Control AndAlso e.KeyCode = Keys.Y Then
            Redo()
            e.Handled = True
        ElseIf e.KeyCode = Keys.Delete Then
            DeleteSelectedTiles()
            e.Handled = True
        End If
    End Sub
#End Region

#Region " Undo Redo "
    Public Sub AddAction(action As MapAction)
        undoRedoManager.AddAction(action)
    End Sub


    Public Sub AddTile(tile As MapTile)
        AddTileInternal(tile)
        undoRedoManager.AddAction(New AddTileAction(tile, Me))
        Invalidate()
    End Sub

    Public Sub AddTileInternal(tile As MapTile)
        _tiles.Add(tile)
    End Sub

    Public Sub RemoveTile(tile As MapTile)
        If RemoveTileInternal(tile) Then
            undoRedoManager.AddAction(New RemoveTileAction(tile, Me))
            Invalidate()
        End If
    End Sub

    Public Function RemoveTileInternal(tile As MapTile) As Boolean
        Return _tiles.Remove(tile)
    End Function

    Public Sub MoveTile(tile As MapTile, newPosition As Point)
        Dim oldPosition As Point = tile.Position
        tile.Position = newPosition
        undoRedoManager.AddAction(New MoveTileAction(tile, Me, oldPosition, newPosition))
        Invalidate()
    End Sub
    Public Sub ResizeTile(tile As MapTile, newSize As Size)
        Dim oldSize As Size = tile.Size
        tile.Size = newSize
        undoRedoManager.AddAction(New ResizeTileAction(tile, Me, oldSize, newSize))
        Invalidate()
    End Sub
    Public Sub Undo()
        undoRedoManager.Undo()
    End Sub

    Public Sub Redo()
        undoRedoManager.Redo()
    End Sub

    Private Sub mnuWalkable_Click(sender As Object, e As EventArgs) Handles mnuWalkable.Click
        If selectedTiles.Count > 0 Then
            ' Toggle the walkable state for all selected tiles
            For Each tile In selectedTiles
                tile.IsWalkable = Not tile.IsWalkable
            Next

            ' Update the menu item check state
            mnuWalkable.Checked = selectedTiles(0).IsWalkable

            ' Refresh the canvas to show/hide the overlay
            Refresh()
            RaiseEvent CanvasModified()
        Else
            MessageBox.Show("No tile selected.", "Walkable", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub
#End Region


End Class


can you see why, when I group tiles together and save the map. The next time I open the map the grouped tiles are there but there is no images? They are just blank