﻿Option Strict On
Option Explicit On

Imports System
Imports System.Collections.Generic
Imports System.Windows.Forms

''' <summary>
''' Main Nexamas.UI developer showcase shell.
''' The launcher consumes MASApplicationWindow.Pages as the official same-window
''' ApplicationSystem route. The Showcase owns only presentation metadata and
''' demo-page selection; Nexamas.UI owns the shell, tree, workspace, layout,
''' sizing, themes, surfaces, and all control rendering.
''' </summary>
Partial Friend Class NexamasUIShowcase

    Private Const HomePageId As String = "showcase.home"
    Private Const GuidedJourneyPageId As String = "showcase.guided.journey"
    Private Const GuidedJourneyDefaultId As String = "controls"
    Private Const StartTourCommandId As String = "showcase.tour.start"

    Private _guidedJourneyId As String = GuidedJourneyDefaultId
    Private _guidedJourneyStepIndex As Integer
    Private ReadOnly _pageLifetimes As New List(Of IDisposable)()

    Public Sub New()
        MyBase.New("Nexamas UI Showcase", ShowcaseWindowSizeKind.Launcher)
        InitializeComponent()
        ApplyShowcaseWindowPresentationContract()
        Me.Text = "Nexamas UI Showcase"
        InitializeRuntimeSmokeFromCommandLine()
    End Sub

    Protected Overrides ReadOnly Property IsShowcaseLauncherWindow As Boolean
        Get
            Return True
        End Get
    End Property

    Friend Sub RegisterPageLifetime(lifetime As IDisposable)
        If lifetime Is Nothing Then Return
        _pageLifetimes.Add(lifetime)
    End Sub

    Friend Sub PrepareShowcasePageBuild()
        DisposePageLifetimes()
    End Sub

    Private Sub DisposePageLifetimes()
        Dim firstCleanupFailure As Exception = Nothing

        For index As Integer = _pageLifetimes.Count - 1 To 0 Step -1
            Dim lifetime As IDisposable = _pageLifetimes(index)
            Try
                If lifetime IsNot Nothing Then lifetime.Dispose()
            Catch ex As Exception
                If firstCleanupFailure Is Nothing Then firstCleanupFailure = ex
            End Try
        Next
        _pageLifetimes.Clear()

        If firstCleanupFailure IsNot Nothing Then
            Throw New InvalidOperationException("A Nexamas.UI page lifetime failed during Showcase cleanup.", firstCleanupFailure)
        End If
    End Sub

    Protected Overrides Sub OnFormClosed(e As FormClosedEventArgs)
        Dim closeFailure As Exception = Nothing

        Try
            DisposePageLifetimes()
        Catch ex As Exception
            closeFailure = ex
        End Try

        Try
            MyBase.OnFormClosed(e)
        Catch ex As Exception
            If closeFailure Is Nothing Then closeFailure = ex
        End Try

        If IsRuntimeSmokeActive() Then
            FinalizeRuntimeSmokeAfterHostClosed(closeFailure)
        ElseIf closeFailure IsNot Nothing Then
            Throw closeFailure
        End If
    End Sub
End Class
