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

Public Class FrmWorld
    Private dragBoxFromMouseDown As Rectangle ' Variable to track the drag 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"}

#Region " Initiate "
    Private Sub FrmWorld_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        PopulateTreeView("D:\01 - Grags\Visual Studio\Bizarria New\Data\Decor")
        ' Ensure PicCanvas can accept drops (if not already set in MapCanvas class)
        PicCanvas.AllowDrop = True

        ' Add event handler for grid size selection
        AddHandler CboDimensions.SelectedIndexChanged, AddressOf CboDimensions_SelectedIndexChanged

        ' Set default grid size
        CboDimensions.SelectedItem = "32 x 32"

        ' Add "10000 x 10000" to the combo box if not already present
        Dim defaultMapSize As String = "15000 x 10000"

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

        ' Set default map size
        CboMapSize.SelectedItem = defaultMapSize

        ' Handle CanvasModified event
        AddHandler PicCanvas.CanvasModified, AddressOf CanvasModified_Handler
        AddHandler cboSearch.KeyDown, AddressOf CboSearch_KeyDown
        AddHandler cboSearch.SelectedIndexChanged, AddressOf CboSearch_SelectedIndexChanged

        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
            ' Populate the ComboBox
            cboSearch.Items.Clear()
            For Each searchTerm As String In recentSearches
                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)

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

                ' Restore selected node
                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
        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

        For Each imageFile As FileInfo In imageFiles
            Await Task.Run(Sub()
                               ' Create an instance of the ImageItem control
                               Dim imageItem As New ImageItem() With {
                                .Image = Image.FromFile(imageFile.FullName),
                                .Filename = imageFile.Name, ' Display only the file name, not the full path
                                .FilePath = imageFile.FullName,
                                .Width = 100, ' Adjust as needed
                                .Height = 120 ' Adjust to accommodate image and label
                            }
                               ' Add event handlers for drag initiation
                               AddHandler imageItem.ImageItemMouseDownEvent, AddressOf ImageItem_MouseDown
                               AddHandler imageItem.ImageItemMouseMoveEvent, AddressOf ImageItem_MouseMove
                               AddHandler imageItem.ImageItemMouseUpEvent, AddressOf ImageItem_MouseUp
                               FLPImages.Invoke(Sub() FLPImages.Controls.Add(imageItem))
                           End Sub)
        Next
    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 "

    ' MouseDown event handler for ImageItem in FLPImages
    Private Sub ImageItem_MouseDown(sender As Object, e As MouseEventArgs)
        If e.Button = MouseButtons.Left Then
            ' Remember the point where the mouse down occurred
            Dim dragSize As Size = SystemInformation.DragSize
            ' Create a rectangle representing the area the mouse can move before a drag starts
            dragBoxFromMouseDown = New Rectangle(New Point(e.X - (dragSize.Width \ 2),
                                                       e.Y - (dragSize.Height \ 2)),
                                             dragSize)
        Else
            ' Reset drag rectangle
            dragBoxFromMouseDown = Rectangle.Empty
        End If
    End Sub

    ' MouseMove event handler for ImageItem in FLPImages
    Private Sub ImageItem_MouseMove(sender As Object, e As MouseEventArgs)
        If (e.Button And MouseButtons.Left) = MouseButtons.Left Then
            ' Check if the mouse has moved outside the drag rectangle
            If dragBoxFromMouseDown <> Rectangle.Empty AndAlso Not dragBoxFromMouseDown.Contains(e.Location) Then
                Dim imageItem As ImageItem = CType(sender, ImageItem)
                ' Get the image from the ImageItem
                Dim image As Image = imageItem.Image
                If image IsNot Nothing Then
                    ' Set custom cursor
                    Dim cursor As Cursor = CreateCursorFromImage(image)
                    Cursor.Current = cursor

                    ' Use standard data format to pass the image and file path
                    Dim dataObj As New DataObject()
                    dataObj.SetData(GetType(Bitmap), image) ' Set the image data with the Bitmap type
                    Dim imageFilePath As String = imageItem.FilePath
                    dataObj.SetData("ImageFilePath", imageFilePath) ' Set the image file path

                    ' Start the drag-and-drop operation
                    imageItem.DoDragDrop(dataObj, DragDropEffects.Copy)

                    ' Reset cursor after dragging
                    Cursor.Current = Cursors.Default

                    ' Dispose of the custom cursor to release resources
                    cursor.Dispose()
                End If
                ' Reset drag rectangle
                dragBoxFromMouseDown = Rectangle.Empty
            End If
        End If
    End Sub
    ' MouseUp event handler for ImageItem in FLPImages
    Private Sub ImageItem_MouseUp(sender As Object, e As MouseEventArgs)
        ' Reset drag rectangle
        dragBoxFromMouseDown = Rectangle.Empty
    End Sub

    ' Helper function to convert Image to Cursor
    Private Function CreateCursorFromImage(image As Image) As Cursor
        Try
            ' Resize the image to a reasonable cursor size, e.g., 32x32
            Dim cursorSize As Integer = 32
            ' Create a new bitmap with 32bppArgb pixel format
            Using bitmap As New Bitmap(cursorSize, cursorSize, PixelFormat.Format32bppArgb)
                Using g As Graphics = Graphics.FromImage(bitmap)
                    ' Set interpolation mode
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic
                    ' Draw the image scaled to the cursor size
                    g.DrawImage(image, New Rectangle(0, 0, cursorSize, cursorSize))
                End Using

                ' Now create a cursor from the bitmap
                Dim iconHandle As IntPtr = bitmap.GetHicon()

                ' Create a cursor from the icon handle
                Dim cursor As Cursor = New Cursor(iconHandle)

                ' It's important to destroy the icon handle to prevent memory leaks
                DestroyIcon(iconHandle)

                Return cursor
            End Using
        Catch ex As Exception
            ' Handle exception by logging or showing a message
            MessageBox.Show("Error creating cursor: " & ex.Message)
            ' Return the default cursor as a fallback
            Return Cursors.Default
        End Try
    End Function

    ' PInvoke declaration to destroy the icon handle and prevent memory leaks
    <DllImport("user32.dll", CharSet:=CharSet.Auto)>
    Private Shared Function DestroyIcon(ByVal hIcon As IntPtr) As Boolean
    End Function

    ' Event handler for CanvasModified event
    Private Sub CanvasModified_Handler()
        isModified = True
    End Sub
#End Region

#Region " CTMTrvFIles "
    ' Event handler for MnuCollapse Click
    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
            MessageBox.Show("Please select a node to collapse.", "Collapse Node", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    ' Event handler for MnuExpand Click
    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
            MessageBox.Show("Please select a node to expand.", "Expand Node", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub
    ' Recursive method to expand all child nodes of a given node
    Private Sub ExpandAllNodes(node As TreeNode)
        node.Expand()
        For Each childNode As TreeNode In node.Nodes
            ExpandAllNodes(childNode)
        Next
    End Sub

    ' Recursive method to collapse all child nodes of a given node
    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
        ' Cancel any existing search
        If searchCancellationTokenSource IsNot Nothing AndAlso Not searchCancellationTokenSource.IsCancellationRequested Then
            searchCancellationTokenSource.Cancel()
        End If

        ' Initialize a new CancellationTokenSource
        searchCancellationTokenSource = New CancellationTokenSource()
        Dim token As CancellationToken = searchCancellationTokenSource.Token

        ' Clear previous search results
        FLPImages.Controls.Clear()

        ' Make the progress bar and cancel button visible
        PrgSearchProgress.Visible = True
        PrgSearchProgress.Style = ProgressBarStyle.Marquee ' Use marquee style

        Try
            ' Perform the search asynchronously
            Dim matchingFiles As New List(Of FileInfo)
            Await Task.Run(Sub()
                               ' Search logic here
                               SearchAllDirectories(searchTerm, matchingFiles, token)
                           End Sub)

            ' Update progress bar to determinate style
            PrgSearchProgress.Style = ProgressBarStyle.Continuous
            PrgSearchProgress.Minimum = 0
            ' Limit the maximum progress to the MaxImagesToDisplay
            PrgSearchProgress.Maximum = Math.Min(matchingFiles.Count, MaxImagesToDisplay)
            PrgSearchProgress.Value = 0

            ' Create a Progress handler
            Dim progressHandler As New Progress(Of ImageItem)(Sub(imageItem)
                                                                  ' This code runs on the UI thread
                                                                  FLPImages.Controls.Add(imageItem)
                                                              End Sub)

            ' Load matching images asynchronously, passing the progress handler
            Await LoadImagesFromFilesAsync(matchingFiles, token, progressHandler)

            If Not token.IsCancellationRequested Then
                AddSearchToRecent(searchTerm)
            End If
        Catch ex As OperationCanceledException
            ' Search was canceled
        Finally
            ' Hide the progress bar and cancel button
            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

        Parallel.ForEach(directoriesToSearch, Sub(directory)
                                                  If token.IsCancellationRequested Then Return
                                                  SearchDirectory(directory, searchTerm, matchingFiles, token)
                                              End Sub)
    End Sub
    ' Recursive method to search directories
    Private Sub SearchDirectory(directory As DirectoryInfo, searchTerm As String, matchingFiles As List(Of FileInfo), token As CancellationToken)
        If token.IsCancellationRequested Then Return

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

            ' Search for matching files
            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

            ' Recursively search subdirectories
            For Each subDirectory As DirectoryInfo In directory.GetDirectories()
                If token.IsCancellationRequested Then Return
                SearchDirectory(subDirectory, searchTerm, matchingFiles, token)
            Next
        Catch ex As UnauthorizedAccessException
            ' Handle or log if necessary
        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)
            ' Get image files in this directory
            Dim imageFiles As List(Of FileInfo) = GetImageFilesFromDirectory(directoryInfo)

            ' Check if file name contains the search term
            For Each imageFile As FileInfo In imageFiles
                If imageFile.Name.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase) >= 0 Then
                    matchingFiles.Add(imageFile)
                End If
            Next

            ' Now search child nodes
            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
    ' Load images from files asynchronously
    Private Async Function LoadImagesFromFilesAsync(imageFiles As List(Of FileInfo), token As CancellationToken, progress As IProgress(Of ImageItem)) As Task
        ' Limit the number of images to display
        Dim imagesToLoad = imageFiles.Take(MaxImagesToDisplay).ToList()
        Dim loadedImagesCount As Integer = 0

        ' Update progress bar maximum on the UI thread
        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
                ' Load the image in a background task
                Dim image As Image = Await Task.Run(Function() Image.FromFile(imageFile.FullName), token)

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

                ' Add event handlers
                AddHandler imageItem.ImageItemMouseDownEvent, AddressOf ImageItem_MouseDown
                AddHandler imageItem.ImageItemMouseMoveEvent, AddressOf ImageItem_MouseMove
                AddHandler imageItem.ImageItemMouseUpEvent, AddressOf ImageItem_MouseUp

                ' Report progress to update UI
                progress.Report(imageItem)

                ' Update the progress bar on the UI thread
                loadedImagesCount += 1
                Invoke(Sub()
                           PrgSearchProgress.Value = loadedImagesCount
                       End Sub)
            Catch ex As Exception
                ' Handle exceptions if necessary
            End Try
        Next
    End Function
    Private Sub AddSearchToRecent(searchTerm As String)
        If recentSearches.Contains(searchTerm) Then
            recentSearches.Remove(searchTerm)
        End If
        recentSearches.Insert(0, searchTerm)

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

        ' Update the ComboBox cboSearch
        isUpdatingComboBox = True
        cboSearch.Items.Clear()
        For Each term As String In recentSearches
            cboSearch.Items.Add(term)
        Next
        isUpdatingComboBox = False
    End Sub
#End Region
#Region " Zoom "
    Private Sub PicCanvas_ZoomLevelChanged(zoomLevel As Single) Handles PicCanvas.ZoomLevelChanged
        ' Update the lblZoom label
        lblZoom.Text = "Zoom: " & (zoomLevel * 100).ToString("0.##") & "%"
    End Sub
#End Region

#Region " ToolStrip "
    ' Click event handler for the "Zoom to Fit" button
    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
                ' Update grid size in PicCanvas
                PicCanvas.GridSize = size
                ' Optionally, update existing tiles to snap to new grid
                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
                ' Update map size
                PicCanvas.SetMapSize(width, height)
            End If
        End If
    End Sub

#End Region

#Region " Save and Load Functionality "

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

    <Serializable>
    Public Class MapTileData
        Public Property ImageFilePath As String
        Public Property Position As Point
        Public Property Size As Size
    End Class

    Private Sub SaveCanvas(fileName As String)
        ' Create CanvasData object
        Dim canvasData As New CanvasData With {
            .GridSize = PicCanvas.GridSize,
            .MapSize = PicCanvas.AutoScrollMinSize,
            .MapTiles = New List(Of MapTileData)()
        }

        ' Map tiles
        For Each tile As MapTile In PicCanvas.Tiles
            Dim tileData As New MapTileData With {
                .ImageFilePath = tile.ImageFilePath,
                .Position = tile.Position,
                .Size = tile.Size
            }
            canvasData.MapTiles.Add(tileData)
        Next

        ' Serialize to XML
        Dim serializer As New XmlSerializer(GetType(CanvasData))

        Using writer As New StreamWriter(fileName)
            serializer.Serialize(writer, canvasData)
        End Using

        isModified = False
    End Sub

    Private Sub LoadCanvas(fileName As String)
        ' Deserialize from XML
        Dim serializer As New XmlSerializer(GetType(CanvasData))
        Using reader As New StreamReader(fileName)
            Dim canvasData As CanvasData = CType(serializer.Deserialize(reader), CanvasData)

            ' Clear existing tiles
            PicCanvas.ClearTiles()

            ' Set grid size and map size
            PicCanvas.GridSize = canvasData.GridSize
            PicCanvas.SetMapSize(canvasData.MapSize.Width, canvasData.MapSize.Height)

            ' Load tiles
            For Each tileData As MapTileData In canvasData.MapTiles
                ' Load image from file path
                If File.Exists(tileData.ImageFilePath) Then
                    Dim image As Image = Image.FromFile(tileData.ImageFilePath)
                    Dim tileImage As New Bitmap(image, tileData.Size)

                    Dim mapTile As New MapTile With {
                        .Image = tileImage,
                        .ImageFilePath = tileData.ImageFilePath,
                        .Position = tileData.Position,
                        .Size = tileData.Size
                    }

                    PicCanvas.AddTile(mapTile)
                Else
                    ' Handle missing image file
                    Dim unused = MessageBox.Show("Image file not found: " & tileData.ImageFilePath)
                End If
            Next
        End Using

        isModified = False
    End Sub

    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 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 (*.*)|*.*"
            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 (*.*)|*.*"
            If ofd.ShowDialog() = DialogResult.OK Then
                currentFileName = ofd.FileName
                LoadCanvas(currentFileName)
            End If
        End Using
    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)
        ' Set the zoom level on PicCanvas
        PicCanvas.ZoomLevel = zoomLevel
    End Sub
    Private Sub TrvFiles_NodeMouseClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles TrvFiles.NodeMouseClick
        If e.Button = MouseButtons.Right Then
            ' Select the node under the mouse cursor
            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
                    ' Open the folder in Windows Explorer
                    Process.Start("explorer.exe", directoryInfo.FullName)
                Catch ex As Exception
                    MessageBox.Show("Failed to open folder: " & ex.Message)
                End Try
            Else
                MessageBox.Show("Directory does not exist.")
            End If
        Else
            MessageBox.Show("No directory selected.")
        End If
    End Sub

    Private Sub PicCanvas_MouseMove(sender As Object, e As MouseEventArgs) Handles PicCanvas.MouseMove
        ' Convert the mouse position to canvas coordinates
        Dim canvasPoint As Point = PicCanvas.ClientToCanvas(e.Location)
        ' Update the status strip label
        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
        ' Save TreeView state
        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()

        ' Collect expanded nodes
        For Each node As TreeNode In TrvFiles.Nodes
            SaveExpandedNodes(node, state)
        Next

        ' Save selected node
        If TrvFiles.SelectedNode IsNot Nothing Then
            state.SelectedNodePath = TrvFiles.SelectedNode.FullPath
        End If

        ' Serialize to XML
        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

End Class
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging

Public Class MapCanvas
    Inherits UserControl

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

#Region " Variables And Properties "
    ' Event to notify when the zoom level changes
    Public Event ZoomLevelChanged(zoomLevel As Single)

    ' Variables for dragging and resizing
    Private selectedTile As MapTile = Nothing

    Private dragging As Boolean = False
    Private resizing As Boolean = False
    Private initialTilePosition As Point
    Private initialTileSize As Size
    Private initialMousePosition As Point

    ' Variables for selection rectangle
    Private isSelecting As Boolean = False

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

    ' List to store selected tiles
    Private selectedTiles As New List(Of MapTile)

    ' Variables for group resizing
    Private initialSelectedTilesBounds As Rectangle

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

    ' Variables for right-click panning
    Private isPanning As Boolean = False

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

    ' List of all tiles on the canvas
    Private _tiles As New List(Of MapTile)

    ' Grid size (default is 32)
    Private _gridSize As Integer = 32

    ' Flag to enable or disable snapping
    Private snappingEnabled As Boolean = True

    ' Flag to show or hide the grid
    Private _showGrid As Boolean = True

    ' Map dimensions
    Private _mapWidth As Integer = 15000

    Private _mapHeight As Integer = 10000

    ' Zoom level (default is 1.0)
    Private _zoomLevel As Single = 1.0F

    ' Event to notify when the canvas is modified
    Public Event CanvasModified()

    ' Property to adjust grid size
    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

    ' Property to show or hide the grid
    Public Property ShowGrid As Boolean
        Get
            Return _showGrid
        End Get
        Set(value As Boolean)
            _showGrid = value
            Invalidate()
        End Set
    End Property

    ' Property to access the tiles
    Public ReadOnly Property Tiles As List(Of MapTile)
        Get
            Return _tiles
        End Get
    End Property

    ' Property to adjust the zoom level
    Public Property ZoomLevel As Single
        Get
            Return _zoomLevel
        End Get
        Set(value As Single)
            ' Remove lower limit constraint or adjust it
            If value <= 0 Then ' Ensure zoom level is positive
                value = 0.01F ' Set to a very small positive value
            End If

            If _zoomLevel <> value Then
                Dim oldZoomLevel As Single = _zoomLevel
                _zoomLevel = value
                AdjustScrollPosition(oldZoomLevel, Nothing)
                UpdateScrollBars()
                Invalidate()
                ' Raise the ZoomLevelChanged event
                RaiseEvent ZoomLevelChanged(_zoomLevel)
            End If
        End Set
    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 ' Enable AutoScroll
        TabStop = True    ' Allow control to receive focus
        ContextMenuStrip = Nothing ' Ensure no default context menu
    End Sub

#End Region

#Region " Drawing Methods "

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

        Dim g As Graphics = e.Graphics

        ' Fill the background with a solid color
        g.Clear(Color.White) ' Choose any color you prefer

        ' Set graphics options to prevent gaps
        g.InterpolationMode = InterpolationMode.NearestNeighbor
        g.PixelOffsetMode = PixelOffsetMode.Half
        g.SmoothingMode = SmoothingMode.None

        ' Save the current state of the Graphics object
        Dim state As GraphicsState = g.Save()

        ' Apply transformations
        g.TranslateTransform(AutoScrollPosition.X, AutoScrollPosition.Y)
        g.ScaleTransform(ZoomLevel, ZoomLevel)

        ' Snap to the nearest whole pixel after scaling
        g.PixelOffsetMode = PixelOffsetMode.None

        ' Draw the grid and tiles
        DrawGrid(g)
        DrawTiles(g)

        ' Restore the graphics state to undo the transforms
        g.Restore(state)

        ' Draw selection rectangle and handles in client coordinates
        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

    ' Draw the grid
    Private Sub DrawGrid(g As Graphics)
        If Not _showGrid Then Exit Sub

        ' Set up the pen for grid lines
        Using pen As New Pen(Color.LightGray)
            ' Adjust pen width based on zoom level to maintain consistent appearance
            pen.Width = 1 / ZoomLevel

            ' Determine the visible area in canvas coordinates
            Dim visibleRect As Rectangle = GetVisibleCanvasRectangle()

            ' Adjust starting positions to align with the grid
            Dim startX As Integer = visibleRect.Left - (visibleRect.Left Mod _gridSize)
            Dim startY As Integer = visibleRect.Top - (visibleRect.Top Mod _gridSize)

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

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

        ' Draw the border around the grid
        DrawGridBorder(g)
    End Sub

    ' Draw a thick black border around the grid edges
    Private Sub DrawGridBorder(g As Graphics)
        ' Create a rectangle representing the grid area
        Dim gridRect As New Rectangle(0, 0, _mapWidth, _mapHeight)

        ' Draw the border
        Using pen As New Pen(Color.Black)
            ' Adjust pen width based on zoom level
            pen.Width = 4 / ZoomLevel
            g.DrawRectangle(pen, gridRect)
        End Using
    End Sub

    ' Draw the tiles
    Private Sub DrawTiles(g As Graphics)
        For Each tile In _tiles
            ' Ensure integer positions and sizes
            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))
            ' Draw tile
            g.DrawImage(tile.Image, tileRect)

            ' Draw selection rectangle
            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
    ' Draw selection rectangle
    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

    ' Draw resize handles for a single tile
    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)
                ' Top-left corner
                DrawHandle(g, brush, pen, screenRect.Left - (handleSize \ 2), screenRect.Top - (handleSize \ 2), handleSize)
                ' Top-right corner
                DrawHandle(g, brush, pen, screenRect.Right - (handleSize \ 2), screenRect.Top - (handleSize \ 2), handleSize)
                ' Bottom-left corner
                DrawHandle(g, brush, pen, screenRect.Left - (handleSize \ 2), screenRect.Bottom - (handleSize \ 2), handleSize)
                ' Bottom-right corner
                DrawHandle(g, brush, pen, screenRect.Right - (handleSize \ 2), screenRect.Bottom - (handleSize \ 2), handleSize)
            End Using
        End Using
    End Sub

    ' Draw resize handles for group of tiles
    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)
                ' Top-left corner
                DrawHandle(g, brush, pen, screenRect.Left - (handleSize \ 2), screenRect.Top - (handleSize \ 2), handleSize)
                ' Top-right corner
                DrawHandle(g, brush, pen, screenRect.Right - (handleSize \ 2), screenRect.Top - (handleSize \ 2), handleSize)
                ' Bottom-left corner
                DrawHandle(g, brush, pen, screenRect.Left - (handleSize \ 2), screenRect.Bottom - (handleSize \ 2), handleSize)
                ' Bottom-right corner
                DrawHandle(g, brush, pen, screenRect.Right - (handleSize \ 2), screenRect.Bottom - (handleSize \ 2), handleSize)
            End Using
        End Using
    End Sub

    ' Helper method to draw a resize handle
    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 "

    ' Handle left mouse button down
    Private Sub HandleLeftMouseDown(e As MouseEventArgs, currentPoint As Point, clickedTile As MapTile)
        If selectedTiles.Count > 1 Then
            ' Check if over group resize handles first
            Dim groupDirection As MapTile.ResizeDirections = GetGroupResizeDirection(currentPoint)
            If groupDirection <> MapTile.ResizeDirections.None Then
                ' Start group resizing
                StartGroupResizing(currentPoint, groupDirection)
                Return
            End If
        End If

        ' If not over group resize handles, proceed
        If clickedTile IsNot Nothing Then
            HandleTileClick(e, currentPoint, clickedTile)
        Else
            ' No tile clicked - start selection rectangle
            StartSelection(currentPoint)
        End If
    End Sub

    ' Handle right mouse button up
    Private Sub HandleRightMouseUp(e As MouseEventArgs)
        ' Adjust current point for scrolling and zoom
        Dim currentPoint As Point = ClientToCanvas(e.Location)
        Dim clickedTile As MapTile = GetTileAtPoint(currentPoint)

        If clickedTile IsNot Nothing Then
            ' Select the tile
            If Not selectedTiles.Contains(clickedTile) Then
                DeselectAllTiles()
                selectedTile = clickedTile
                selectedTile.Selected = True
                selectedTiles.Clear()
                selectedTiles.Add(selectedTile)
            End If

            ' Bring the selected tile to the front
            BringTileToFront(selectedTile)

            Refresh()

            ' Show the context menu at the mouse location
            CTMMenu.Show(Me, e.Location)
        Else
            ' No tile was right-clicked; do not show context menu
            ' Optionally, deselect all tiles
            ' DeselectAllTiles()
            ' Refresh()
        End If
    End Sub

    ' Handle dragging
    Private Sub HandleDragging(currentPoint As Point)
        Dim deltaX As Integer = currentPoint.X - initialMousePosition.X
        Dim deltaY As Integer = currentPoint.Y - initialMousePosition.Y

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

            ' Apply snapping if enabled and Shift is NOT pressed
            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

            ' Clamp the position to be within the map boundaries
            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

    ' Handle resizing
    Private Sub HandleResizing(currentPoint As Point)
        If selectedTiles.Count = 1 Then
            ' Single tile resizing
            ResizeSingleTile(currentPoint)
        Else
            ' Group resizing
            ResizeGroupTiles(currentPoint)
        End If
    End Sub

    ' Update cursor based on mouse position
    Private Sub UpdateCursor(currentPoint As Point)
        ' Convert the mouse point to canvas coordinates
        Dim canvasPoint As Point = ClientToCanvas(currentPoint)

        Dim cursorSet As Boolean = False

        ' Check if over group resize handles
        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

        ' Check if over resize handles of any tile
        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

    ' Handle mouse events for selecting and moving tiles
    Protected Overrides Sub OnMouseDown(e As MouseEventArgs)
        MyBase.OnMouseDown(e)

        ' Convert mouse position to canvas coordinates
        Dim currentPoint As Point = ClientToCanvas(e.Location)
        Dim clickedTile As MapTile = GetTileAtPoint(currentPoint)

        If e.Button = MouseButtons.Left Then
            HandleLeftMouseDown(e, currentPoint, clickedTile)
        ElseIf e.Button = MouseButtons.Right Then
            ' Start panning
            isPanning = True
            panStartPoint = e.Location ' Store the mouse position in client coordinates
            scrollStartPoint = AutoScrollPosition
        End If
    End Sub

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

        Dim currentPoint As Point = e.Location

        If resizing Then
            ' Convert mouse position to canvas coordinates
            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
            ' Update selection rectangle
            Dim canvasPoint As Point = ClientToCanvas(currentPoint)
            selectionEndPoint = canvasPoint
            Refresh()
        ElseIf isPanning AndAlso e.Button = MouseButtons.Right Then
            ' Handle panning
            HandlePanning(e.Location)
        Else
            ' Update cursor based on hover over resize handles
            UpdateCursor(currentPoint)
        End If
    End Sub

    Protected Overrides Sub OnMouseUp(e As MouseEventArgs)
        ' For right-click, prevent the base method from displaying the default context menu
        If e.Button <> MouseButtons.Right Then
            MyBase.OnMouseUp(e)
        End If

        ' Handle selection rectangle completion
        If isSelecting Then
            isSelecting = False
            ' Create the selection rectangle
            selectionRectangle = GetSelectionRectangle()
            ' Select tiles within the rectangle
            SelectTilesInRectangle(selectionRectangle)
            Refresh()
        End If

        ' Stop dragging and resizing
        dragging = False
        resizing = False
        If selectedTile IsNot Nothing Then
            selectedTile.IsResizing = False
            selectedTile.CurrentResizeDirection = MapTile.ResizeDirections.None
        End If
        For Each tile In selectedTiles
            tile.CurrentResizeDirection = MapTile.ResizeDirections.None
        Next

        ' Handle right mouse button up event
        If e.Button = MouseButtons.Right Then
            If isPanning Then
                ' Stop panning
                isPanning = False
                Cursor = Cursors.Default
                If hasPanned Then
                    ' If panning occurred, we don't show the context menu
                    hasPanned = False
                Else
                    ' No panning occurred, check if a tile was right-clicked
                    HandleRightMouseUp(e)
                End If
            Else
                ' Not panning, handle right-click
                HandleRightMouseUp(e)
            End If
        End If
    End Sub

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

    ' Handle drag enter event
    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

    ' Handle drag drop event
    Protected Overrides Sub OnDragDrop(drgevent As DragEventArgs)
        MyBase.OnDragDrop(drgevent)
        If drgevent.Data.GetDataPresent(GetType(Bitmap)) Then
            ' Retrieve the image
            Dim image As Image = CType(drgevent.Data.GetData(GetType(Bitmap)), Image)
            ' Retrieve the image file path if available
            Dim imageFilePath As String = Nothing
            If drgevent.Data.GetDataPresent("ImageFilePath") Then
                imageFilePath = CType(drgevent.Data.GetData("ImageFilePath"), String)
            End If
            ' Handle the dropped image
            HandleImageDrop(image, imageFilePath, drgevent)
        ElseIf drgevent.Data.GetDataPresent(DataFormats.FileDrop) Then
            ' Handle file drops (e.g., dragging an image from Explorer)
            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
                        ' Handle exception if file is not an image
                    End Try
                End If
            Next
        End If
    End Sub

    Protected Overrides Sub OnMouseEnter(e As EventArgs)
        MyBase.OnMouseEnter(e)
        ' Set focus only if the control does not already have it
        If Not Me.Focused Then
            Me.Focus()
        End If
    End Sub

    Protected Overrides Sub OnMouseWheel(e As MouseEventArgs)
        ' Ensure the control has focus to receive keyboard and mouse wheel events
        Me.Focus()

        ' Capture the mouse position
        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)
        ' Original image size
        Dim originalSize As Size = image.Size

        ' Calculate the new size by scaling to 50%
        Dim scaledWidth As Double = originalSize.Width * 0.5
        Dim scaledHeight As Double = originalSize.Height * 0.5

        ' Adjust the new size to be exact multiples of the grid size
        Dim newWidth As Integer = CInt(Math.Ceiling(scaledWidth / _gridSize)) * _gridSize
        Dim newHeight As Integer = CInt(Math.Ceiling(scaledHeight / _gridSize)) * _gridSize

        ' Clamp the size to not exceed map boundaries
        newWidth = Math.Min(newWidth, _mapWidth)
        newHeight = Math.Min(newHeight, _mapHeight)

        ' Create a resized image that fits the grid exactly
        Dim resizedImage As New Bitmap(newWidth, newHeight, PixelFormat.Format32bppArgb)
        Using g As Graphics = Graphics.FromImage(resizedImage)
            ' Set graphics options
            g.InterpolationMode = InterpolationMode.NearestNeighbor
            g.PixelOffsetMode = PixelOffsetMode.Half
            g.SmoothingMode = SmoothingMode.None

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

        ' Get the drop coordinates and adjust for scroll position and zoom
        Dim point As Point = PointToClient(New Point(drgevent.X, drgevent.Y))
        point = ClientToCanvas(point)

        ' Apply snapping if enabled and Shift is NOT pressed
        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

        ' Clamp the position to be within the map boundaries
        point.X = Math.Max(0, Math.Min(point.X, _mapWidth - newWidth))
        point.Y = Math.Max(0, Math.Min(point.Y, _mapHeight - newHeight))

        ' Create a new tile and add it to the canvas
        Dim newTile As New MapTile With {
        .Image = resizedImage,
        .ImageFilePath = imageFilePath,
        .Position = point,
        .Size = New Size(newWidth, newHeight)
    }
        AddTile(newTile)
    End Sub

    ' Handle panning
    Private Sub HandlePanning(currentMousePosition As Point)
        ' Calculate the delta movement
        Dim deltaX As Integer = currentMousePosition.X - panStartPoint.X
        Dim deltaY As Integer = currentMousePosition.Y - panStartPoint.Y

        ' Calculate the new scroll position
        Dim newScrollPosition As New Point(scrollStartPoint.X + deltaX, scrollStartPoint.Y + deltaY)

        ' Calculate the scaled map size
        Dim scaledMapWidth As Integer = CInt(_mapWidth * ZoomLevel)
        Dim scaledMapHeight As Integer = CInt(_mapHeight * ZoomLevel)

        ' Calculate maximum scroll positions
        Dim maxScrollX As Integer = Math.Max(0, scaledMapWidth - ClientSize.Width)
        Dim maxScrollY As Integer = Math.Max(0, scaledMapHeight - ClientSize.Height)

        ' Adjust offsetX and offsetY for centering when map is smaller than viewport
        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

        ' Adjust clamping to account for centering
        Dim minScrollX As Integer = -offsetX
        Dim minScrollY As Integer = -offsetY
        Dim maxScrollXWithOffset As Integer = maxScrollX + offsetX
        Dim maxScrollYWithOffset As Integer = maxScrollY + offsetY

        ' Clamp the scroll position to prevent scrolling beyond the content boundaries
        newScrollPosition.X = Math.Max(-maxScrollXWithOffset, Math.Min(-offsetX, newScrollPosition.X))
        newScrollPosition.Y = Math.Max(-maxScrollYWithOffset, Math.Min(-offsetY, newScrollPosition.Y))

        ' Update the scroll position (AutoScrollPosition uses positive values)
        AutoScrollPosition = New Point(-newScrollPosition.X, -newScrollPosition.Y)

        ' Refresh the control to update the display
        Refresh()
    End Sub

    ' Convert client point to canvas point
    Public Function ClientToCanvas(point As Point) As Point
        Return New Point((point.X - AutoScrollPosition.X) / ZoomLevel, (point.Y - AutoScrollPosition.Y) / ZoomLevel)
    End Function

    ' Convert canvas rectangle to client rectangle
    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

    ' Adjust scroll bars based on zoom level
    Private Sub UpdateScrollBars()
        ' Calculate the scaled map size
        Dim scaledWidth As Integer = CInt(_mapWidth * ZoomLevel)
        Dim scaledHeight As Integer = CInt(_mapHeight * ZoomLevel)

        ' Set the AutoScrollMinSize to the scaled map size
        AutoScrollMinSize = New Size(scaledWidth, scaledHeight)

        ' Calculate offsets for centering
        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

        ' Adjust scroll position to keep within bounds
        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?)
        ' By default, use the center of the control as the focus point
        Dim focus As Point = If(focusPoint, New Point(ClientSize.Width / 2, ClientSize.Height / 2))

        ' Convert focus point to canvas coordinates before zoom
        Dim scrollPos As Point = AutoScrollPosition ' Note: AutoScrollPosition values are negative
        Dim offsetX As Integer = 0
        Dim offsetY As Integer = 0

        ' Calculate the scaled map size
        Dim scaledMapWidth As Integer = CInt(_mapWidth * ZoomLevel)
        Dim scaledMapHeight As Integer = 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 focusX As Single = (-scrollPos.X + focus.X - offsetX) / oldZoomLevel
        Dim focusY As Single = (-scrollPos.Y + focus.Y - offsetY) / oldZoomLevel

        ' Update scrollbars to get new AutoScrollMinSize
        UpdateScrollBars()

        ' Recalculate offsets after zoom change
        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

        ' Calculate new scroll positions to keep focus point at the same canvas coordinates
        Dim newScrollX As Integer = CInt(-(focusX * ZoomLevel) + focus.X - offsetX)
        Dim newScrollY As Integer = CInt(-(focusY * ZoomLevel) + focus.Y - offsetY)

        ' Calculate maximum scroll positions
        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

        ' Clamp the scroll positions within allowable ranges
        newScrollX = Math.Max(-maxScrollXWithOffset, Math.Min(-offsetX, newScrollX))
        newScrollY = Math.Max(-maxScrollYWithOffset, Math.Min(-offsetY, newScrollY))

        ' Update AutoScrollPosition (note that setting AutoScrollPosition uses positive values)
        AutoScrollPosition = New Point(-newScrollX, -newScrollY)
    End Sub

    ' Method to bring a tile to the front
    Private Sub BringTileToFront(tile As MapTile)
        If _tiles.Remove(tile) Then
            _tiles.Add(tile)
            Invalidate()
        End If
    End Sub

    ' Method to send a tile to the back
    Private Sub SendTileToBack(tile As MapTile)
        If _tiles.Remove(tile) Then
            _tiles.Insert(0, tile)
            Invalidate()
        End If
    End Sub

    ' Method to delete selected tiles
    Private Sub DeleteSelectedTiles()
        For Each tile In selectedTiles
            Dim unused = _tiles.Remove(tile)
        Next
        DeselectAllTiles()
        Invalidate()
        RaiseEvent CanvasModified()
    End Sub

    ' Get the tile at a specific point
    Private Function GetTileAtPoint(point As Point) As MapTile
        For i As Integer = _tiles.Count - 1 To 0 Step -1 ' Start from topmost tile
            Dim tile = _tiles(i)
            ' Check if point is within tile rectangle
            Dim rect As New Rectangle(tile.Position, tile.Size)
            If rect.Contains(point) Then
                Return tile
            Else
                ' Check if point is within the tile's resize handles
                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 ' Same as the handle size used in drawing
        Dim adjustedHandleSize As Single = handleSize / ZoomLevel

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

        ' Define rectangles for the handles
        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)

        ' Check if point is within any of the handles
        If topLeftHandle.Contains(point) OrElse topRightHandle.Contains(point) OrElse bottomLeftHandle.Contains(point) OrElse bottomRightHandle.Contains(point) Then
            Return True
        End If

        Return False
    End Function

    ' Determine if mouse is over resize handles of a tile
    Private Function GetResizeDirection(tile As MapTile, canvasPoint As Point) As MapTile.ResizeDirections
        Dim handleSize As Integer = 6 ' Should match the handle size used in drawing

        ' Adjust handle size based on zoom level to match the display
        Dim adjustedHandleSize As Single = handleSize / ZoomLevel

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

        ' Define rectangles for the handles
        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)

        ' Check which handle contains the point
        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

    ' Determine if mouse is over group resize handles
    Private Function GetGroupResizeDirection(canvasPoint As Point) As MapTile.ResizeDirections
        If selectedTiles.Count <= 1 Then Return MapTile.ResizeDirections.None

        Dim handleSize As Integer = 6 ' Should match the handle size used in drawing

        ' Adjust handle size based on zoom level
        Dim adjustedHandleSize As Single = handleSize / ZoomLevel

        Dim bounds = GetSelectedTilesBounds()

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

        ' Define rectangles for the handles
        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)

        ' Check which handle contains the point
        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

    ' Get the bounding rectangle of selected tiles
    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

    ' Get cursor based on resize direction
    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

    ' Helper methods for selection rectangle
    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 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

    ' Method to set the map size
    Public Sub SetMapSize(width As Integer, height As Integer)
        _mapWidth = width
        _mapHeight = height

        ' Adjust tiles that are outside new boundaries
        For Each tile In _tiles
            ' Adjust position
            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)

            ' Adjust size if necessary
            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

            ' Ensure minimum size
            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

    ' Method to snap all tiles to grid
    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

    ' ReadOnly properties for key detection
    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 "

    ' Zoom in method
    Private Sub ZoomIn(ByVal focusPoint As Point?)
        ' Increase zoom level
        ZoomLevel *= 1.1F ' Increase by 10%
    End Sub

    Private Sub ZoomOut(ByVal focusPoint As Point?)
        ' Decrease zoom level
        ZoomLevel /= 1.1F ' Decrease by approx 10%
    End Sub

    ' Method to zoom out to fit the entire map within the viewport
    Public Sub ZoomToFit()
        ' Calculate the zoom levels needed to fit the width and height
        Dim zoomX As Single = Me.ClientSize.Width / _mapWidth
        Dim zoomY As Single = Me.ClientSize.Height / _mapHeight

        ' Choose the smaller zoom level to ensure the entire map fits
        Dim newZoomLevel As Single = Math.Min(zoomX, zoomY)

        ' Ensure zoom level is positive and non-zero
        If newZoomLevel <= 0 Then
            newZoomLevel = 0.01F ' Set to a very small positive value
        End If

        ' Set the new zoom level
        Dim oldZoomLevel As Single = _zoomLevel
        _zoomLevel = newZoomLevel
        AdjustScrollPosition(oldZoomLevel, New Point(ClientSize.Width / 2, ClientSize.Height / 2))
        UpdateScrollBars()
        Invalidate()
        ' Raise the ZoomLevelChanged event
        RaiseEvent ZoomLevelChanged(_zoomLevel)
    End Sub

#End Region

#Region " CTMMenu "

    ' Event handler for Send to Back menu item
    Private Sub MnuSendToBack_Click(sender As Object, e As EventArgs) Handles MnuSendToBack.Click
        If selectedTiles.Count > 0 Then
            For Each tile In selectedTiles
                SendTileToBack(tile)
            Next
            Refresh()
        End If
    End Sub

    ' Event handler for Delete menu item
    Private Sub MnuDelete_Click(sender As Object, e As EventArgs) Handles MnuDelete.Click
        If selectedTiles.Count > 0 Then
            DeleteSelectedTiles()
        End If
    End Sub

    ' Event handler for Rotate 90° menu item
    Private Sub MnuRotate90_Click(sender As Object, e As EventArgs) Handles MnuRotate90.Click
        If selectedTiles.Count > 0 Then
            RotateSelectedTiles(90)
            Refresh()
            RaiseEvent CanvasModified()
        End If
    End Sub
    ' Event handler for Group menu item
    Private Sub MnuGroup_Click(sender As Object, e As EventArgs) Handles MnuGroup.Click
        If selectedTiles.Count > 1 Then
            GroupSelectedTiles()
            Refresh()
        Else
            MessageBox.Show("Please select at least two tiles to group.", "Group Tiles", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub
    Private Sub GroupSelectedTiles()
        ' Get the bounding rectangle of selected tiles
        Dim bounds As Rectangle = GetSelectedTilesBounds()

        ' Create a new bitmap of the size of the bounding rectangle
        Dim mergedImage As New Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb)
        Using g As Graphics = Graphics.FromImage(mergedImage)
            ' Set graphics options
            g.InterpolationMode = InterpolationMode.NearestNeighbor
            g.PixelOffsetMode = PixelOffsetMode.Half
            g.SmoothingMode = SmoothingMode.None

            ' Clear the bitmap to transparent
            g.Clear(Color.Transparent)

            ' Draw the selected tiles in order of their z-index (layering order)
            ' To preserve layering, draw from the bottom up
            For Each tile In Tiles
                If tile.Selected Then
                    ' Compute the offset position relative to the bounding rectangle
                    Dim offsetX As Integer = tile.Position.X - bounds.X
                    Dim offsetY As Integer = tile.Position.Y - bounds.Y

                    ' Draw the tile's image onto the merged image
                    g.DrawImage(tile.Image, New Rectangle(offsetX, offsetY, tile.Size.Width, tile.Size.Height))
                End If
            Next
        End Using

        ' Create a new MapTile with the merged image
        Dim newTile As New MapTile With {
        .Image = mergedImage,
        .Position = New Point(bounds.X, bounds.Y),
        .Size = mergedImage.Size,
        .Selected = True
    }

        ' Remove the selected tiles from the Tiles list
        Tiles.RemoveAll(Function(t) t.Selected)

        ' Add the new tile to the Tiles list
        Tiles.Add(newTile)

        ' Clear the selectedTiles list and add the new tile to it
        selectedTiles.Clear()
        selectedTiles.Add(newTile)
        selectedTile = newTile

        ' Raise CanvasModified event
        RaiseEvent CanvasModified()
    End Sub
#End Region

#Region " Tile Manipulation Methods "

    ' Rotate selected tiles by specified angle
    Private Sub RotateSelectedTiles(angle As Single)
        For Each tile In selectedTiles
            ' Rotate the image
            Dim rotatedImage As Image = RotateImage(tile.Image, angle)

            ' Adjust the size
            Dim newSize As Size = rotatedImage.Size

            ' Calculate new position to maintain the center point
            Dim oldCenter As New Point(tile.Position.X + (tile.Size.Width / 2), tile.Position.Y + (tile.Size.Height / 2))
            Dim newPosition As New Point(oldCenter.X - (newSize.Width / 2), oldCenter.Y - (newSize.Height / 2))

            ' Apply snapping if necessary
            If snappingEnabled AndAlso Not IsShiftKeyPressed Then
                newPosition.X = CInt(newPosition.X / _gridSize) * _gridSize
                newPosition.Y = CInt(newPosition.Y / _gridSize) * _gridSize
            End If

            ' Update the tile's image, size, and position
            tile.Image = rotatedImage
            tile.Size = newSize
            tile.Position = newPosition
        Next
    End Sub

    ' Function to rotate an image by a specified angle
    Private Function RotateImage(img As Image, angle As Single) As Image
        ArgumentNullException.ThrowIfNull(img)

        ' Create a new empty bitmap to hold rotated image
        Dim rotatedBmp As New Bitmap(img.Height, img.Width)
        rotatedBmp.SetResolution(img.HorizontalResolution, img.VerticalResolution)

        ' Make a graphics object from the empty bitmap
        Using g As Graphics = Graphics.FromImage(rotatedBmp)
            ' Move rotation point to center of image
            g.TranslateTransform(rotatedBmp.Width / 2, rotatedBmp.Height / 2)
            ' Rotate
            g.RotateTransform(angle)
            ' Move image back
            g.TranslateTransform(-img.Width / 2, -img.Height / 2)
            ' Draw passed in image onto graphics object
            g.DrawImage(img, New Point(0, 0))
        End Using

        Return rotatedBmp
    End Function

    ' Handle tile click actions
    Private Sub HandleTileClick(e As MouseEventArgs, currentPoint As Point, clickedTile As MapTile)
        ' First, check if over resize handles of the tile
        Dim direction As MapTile.ResizeDirections = GetResizeDirection(clickedTile, currentPoint)
        If direction <> MapTile.ResizeDirections.None Then
            ' Start resizing the tile
            StartSingleTileResizing(clickedTile, currentPoint, direction)
        Else
            ' Proceed with selection or dragging
            If IsCtrlKeyPressed Then
                ' Duplicate the selected tiles
                DuplicateSelectedTiles(currentPoint)
            Else
                If Not selectedTiles.Contains(clickedTile) Then
                    ' Single tile selection
                    DeselectAllTiles()
                    selectedTile = clickedTile
                    selectedTile.Selected = True
                    selectedTiles.Clear()
                    selectedTiles.Add(selectedTile)
                Else
                    selectedTile = clickedTile ' Ensure clickedTile is set as selectedTile
                End If

                ' Initialize variables for dragging
                For Each tile In selectedTiles
                    tile.InitialPosition = tile.Position
                Next
                initialMousePosition = currentPoint

                ' Bring the selected tile to the front
                BringTileToFront(selectedTile)

                dragging = True
                Refresh()
            End If
        End If
    End Sub
    ' Duplicate selected tiles when CTRL + Click
    Private Sub DuplicateSelectedTiles(currentPoint As Point)
        ' List to hold duplicates
        Dim duplicates As New List(Of MapTile)

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

        ' Deselect all tiles
        DeselectAllTiles()

        ' Set the duplicates as the selected tiles
        selectedTiles = duplicates
        For Each tile In selectedTiles
            tile.Selected = True
            tile.InitialPosition = tile.Position
        Next

        initialMousePosition = currentPoint

        ' Bring the duplicated tiles to the front
        For Each tile In selectedTiles
            BringTileToFront(tile)
        Next

        ' Start dragging the duplicates
        dragging = True
        Refresh()
    End Sub
    ' Start selection rectangle
    Private Sub StartSelection(currentPoint As Point)
        isSelecting = True
        selectionStartPoint = currentPoint
        selectionEndPoint = currentPoint
        DeselectAllTiles()
        Refresh()
    End Sub

    ' Start group resizing
    Private Sub StartGroupResizing(currentPoint As Point, groupDirection As MapTile.ResizeDirections)
        resizing = True
        ' Record initial mouse position
        initialMousePosition = currentPoint

        ' Record initial bounds of selected tiles
        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

        ' Set current resize direction
        For Each tile In selectedTiles
            tile.CurrentResizeDirection = groupDirection
        Next

        Refresh()
    End Sub

    ' Start resizing a single tile
    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

        ' Initialize resizing variables
        initialTilePosition = selectedTile.Position
        initialTileSize = selectedTile.Size
        initialMousePosition = currentPoint

        ' Bring the tile to the front
        BringTileToFront(selectedTile)

        Refresh()
    End Sub

    ' Duplicate a tile when CTRL + Click
    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)

        ' Set initial positions for dragging
        initialTilePosition = duplicateTile.Position
        duplicateTile.InitialPosition = duplicateTile.Position
        initialMousePosition = currentPoint

        ' Bring the duplicated tile to the front
        BringTileToFront(selectedTile)

        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

        ' Adjust size and position based on resize direction
        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

        ' Ensure minimum size
        If newSize.Width <= 1 Then newSize.Width = 1
        If newSize.Height <= 1 Then newSize.Height = 1

        ' Apply snapping if enabled and Shift is NOT pressed
        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

        ' Clamp position and size to map boundaries
        If newPosition.X < 0 Then
            newSize.Width += newPosition.X ' Reduce width by the amount it goes over the left edge
            newPosition.X = 0
        End If
        If newPosition.Y < 0 Then
            newSize.Height += newPosition.Y ' Reduce height by the amount it goes over the top edge
            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

        ' Ensure minimum size after clamping
        If newSize.Width <= 1 Then newSize.Width = 1
        If newSize.Height <= 1 Then newSize.Height = 1

        selectedTile.Size = newSize
        selectedTile.Position = newPosition
        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

        ' Adjust bounds based on resize direction
        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

        ' Ensure minimum size
        If newBounds.Width <= 1 Then newBounds.Width = 1
        If newBounds.Height <= 1 Then newBounds.Height = 1

        ' Clamp the new bounds within map boundaries
        If newBounds.X < 0 Then
            newBounds.Width += newBounds.X ' Reduce width
            newBounds.X = 0
        End If
        If newBounds.Y < 0 Then
            newBounds.Height += newBounds.Y ' Reduce height
            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

        ' Ensure minimum size after clamping
        If newBounds.Width <= 1 Then newBounds.Width = 1
        If newBounds.Height <= 1 Then newBounds.Height = 1

        ' Calculate scale factors
        Dim scaleX As Double = newBounds.Width / initialSelectedTilesBounds.Width
        Dim scaleY As Double = newBounds.Height / initialSelectedTilesBounds.Height

        ' Resize and reposition each tile
        For Each item In initialSelectedTilesPositionsAndSizes
            Dim tile = item.Item1
            Dim initialPos = item.Item2
            Dim initialSize = item.Item3

            ' Calculate relative position within the group
            Dim relX As Double = (initialPos.X - initialSelectedTilesBounds.X) / initialSelectedTilesBounds.Width
            Dim relY As Double = (initialPos.Y - initialSelectedTilesBounds.Y) / initialSelectedTilesBounds.Height

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

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

            ' Ensure minimum size
            If newWidth <= 1 Then newWidth = 1
            If newHeight <= 1 Then newHeight = 1

            ' Apply snapping to individual tiles if needed
            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

            ' Clamp individual tile positions and sizes within map boundaries
            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

    ' Handle drag drop action
    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)

        ' Original image size
        Dim originalSize As Size = image.Size

        ' Calculate the new size by snapping to the grid
        Dim newWidth As Integer = CInt(originalSize.Width / _gridSize) * _gridSize
        Dim newHeight As Integer = CInt(originalSize.Height / _gridSize) * _gridSize

        ' Ensure minimum size of one grid unit
        If newWidth < _gridSize Then newWidth = _gridSize
        If newHeight < _gridSize Then newHeight = _gridSize

        ' Create a resized image
        Dim resizedImage As New Bitmap(image, New Size(newWidth, newHeight))

        ' Get the drop coordinates and adjust for scroll position and zoom
        Dim point As Point = PointToClient(New Point(drgevent.X, drgevent.Y))
        point = ClientToCanvas(point)

        ' Apply snapping to position if snapping is enabled and Shift is NOT pressed
        If snappingEnabled AndAlso Not IsShiftKeyPressed Then
            point.X = CInt(point.X / _gridSize) * _gridSize
            point.Y = CInt(point.Y / _gridSize) * _gridSize
        End If

        ' Create a new tile and add it to the canvas
        Dim newTile As New MapTile With {
            .Image = resizedImage,
            .ImageFilePath = imageFilePath,
            .Position = point,
            .Size = resizedImage.Size
        }
        AddTile(newTile)
    End Sub

    ' Method to add a tile
    Public Sub AddTile(tile As MapTile)
        _tiles.Add(tile)
        Invalidate()
        ' Optionally, raise the CanvasModified event if needed
        RaiseEvent CanvasModified()
    End Sub

    ' Method to clear the tiles
    Public Sub ClearTiles()
        _tiles.Clear()
        Invalidate()
    End Sub

#End Region

End Class

I'm making an oldstyle Final Fantasy type game. The above is my Map Editor. I have Downloaded a LOAD of sprite sheets. 
Each sheet contains 12 images 
Size of each image is 32x32
They are split into 4 rows. 
The top row is the character facing towards us
The second row is the character facing left
The third row is the character facing right
and the bottom row is the character facing away from us. 

What I'd like to know from you. Is the best way to implement these characters into my game?