Imports System.Windows.Forms

Public Class frmError
    Public ValidatorError As String = ""
    Private _isClosing As Boolean = False

    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
        ' ========== FIX 1: Event-Handler SOFORT deregistrieren ==========
        RemoveHandler OK_Button.Click, AddressOf OK_Button_Click

        ' ========== DIAGNOSE: StackTrace ausgeben ==========
        Dim st As New StackTrace(True)
        LOGGER.Debug($"[frmError] OK_Button_Click aufgerufen von:")
        For Each frame As StackFrame In st.GetFrames()
            LOGGER.Debug($"  {frame.GetMethod()?.DeclaringType?.Name}.{frame.GetMethod()?.Name} (Zeile {frame.GetFileLineNumber()})")
        Next
        ' ========== ENDE DIAGNOSE ==========

        CloseDialog()
    End Sub

    Private Sub frmError_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If ValidatorError <> String.Empty Or errormessage <> String.Empty Then
            If ValidatorError <> String.Empty Then
                Me.txterror.Text = ValidatorError
            Else
                Me.txterror.Text = errormessage
            End If
            Me.Label1.Focus()
            Me.Timer1.Start()
        Else
            Me.Close()
        End If

    End Sub

    Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
        If Me.OK_Button.Focused Then
            Me.Label1.Focus()
        End If
    End Sub

    Private Sub CloseDialog()
        ' ========== FIX 2: Guard mit Dispose-Check ==========
        If _isClosing OrElse Me.IsDisposed Then
            LOGGER.Debug($"[frmError] CloseDialog blockiert (isClosing={_isClosing}, IsDisposed={Me.IsDisposed})")
            Exit Sub
        End If

        _isClosing = True
        LOGGER.Debug($"[frmError] CloseDialog: Flag gesetzt, starte verzögerten Close")

        ' ========== FIX 3: VERZÖGERTER Close via BeginInvoke ==========
        ' KRITISCH: Close wird NACH Abschluss des aktuellen Event-Handlers ausgeführt
        Me.BeginInvoke(New Action(Sub()
                                      If Not Me.IsDisposed Then
                                          Me.DialogResult = DialogResult.OK
                                          Me.Close()
                                          LOGGER.Debug($"[frmError] Dialog geschlossen via BeginInvoke")
                                      End If
                                  End Sub))
        ' ========== ENDE FIX 3 ==========
    End Sub
    Private Sub frmError_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        Me.Label1.Focus()
        LOGGER.Debug($"[frmError] Dialog angezeigt - Enabled: {Me.Enabled}")
    End Sub

    Private Sub frmError_Activated(sender As Object, e As EventArgs) Handles Me.Activated
        LOGGER.Debug($"[frmError] Dialog aktiviert")
    End Sub
    ' ========== FIX 4: FormClosing-Handler hinzufügen ==========
    Private Sub frmError_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        If _isClosing Then
            LOGGER.Debug($"[frmError] FormClosing: Close bereits aktiv, erlauben")
            Return
        End If

        ' Falls Close von außen (z.B. [X]-Button) ausgelöst wurde
        _isClosing = True
        LOGGER.Debug($"[frmError] FormClosing: Flag gesetzt via FormClosing")
    End Sub
    ' ========== ENDE FIX 4 ==========
End Class
