﻿Option Strict On
Option Explicit On

Imports System
Imports System.Collections.Generic
Imports System.Globalization
Imports System.IO
Imports Nexamas.UI.Application
Imports Nexamas.UI.Components
Imports Nexamas.UI.Components.DropDownMenu
Imports Nexamas.UI.Controls
Imports Nexamas.UI.FileSystem
Imports Nexamas.UI.Icons
Imports Nexamas.UI.Layout
Imports Nexamas.UI.Localization
Imports Nexamas.UI.Output
Imports Nexamas.UI.Theming
Imports Nexamas.UI.TextInput
Imports Nexamas.UI.Verification
Imports SkiaSharp

Partial Friend NotInheritable Class ShowcasePageHostContentBuilder

    Private Shared Function ResolveWorkflowFoundationWizardStepText(stepIndex As Integer) As String
        Select Case Math.Max(0, Math.Min(2, stepIndex))
            Case 0
                Return "Collect: name, contact, role, and enabled state are gathered through public MAS input controls."
            Case 1
                Return "Validate: field state is represented with public validation visuals; internal rule engines stay inside Nexamas.UI."
            Case Else
                Return "Submit: the host application decides whether to continue; Showcase only invokes public action surfaces."
        End Select
    End Function

    Private Shared Sub BuildCertificationCenterSummary(page As MASApplicationLayoutPageBuilder,
                                                        window As MASApplicationWindow)
        Dim status As MASLabel = Heading(window, "Certification Center: consumer-safe commercial summary")
        Dim intro As MASLabel = Body(window, "This Showcase project is an external Nexamas.UI consumer. After the public API lockdown, certification evidence remains Nexamas.UI-owned and is no longer imported through internal certification namespaces or attach helpers. This page keeps the commercial story visible using public controls only. Current consumer-safe coverage includes Chart, PropertyGrid, Advanced SearchBox, Surface Materials, and Services as product-facing summaries, not certification internals.")

        Dim boundaryCard As MASLabel = InfoCard(window, "Public API boundary", "Certification facts are release evidence, not an SDK surface that application developers should compose directly. The Showcase now demonstrates the boundary instead of depending on internal certification host types.")
        Dim releaseCard As MASLabel = InfoCard(window, "Commercial release proof", "The official proof path is the Nexamas.UI quality and commercial gate: build, runtime harness, source contracts, pack, packed consumer, and performance smoke. This page does not run those gates from the demo.")
        Dim buyerCard As MASLabel = InfoCard(window, "Buyer-facing value", "A commercial buyer should see a clean product surface: application shell, controls, layout pages, themes, materials, RTL, render verification, data views, and service facades. Internal evidence stays sealed.")
        Dim noParallelCard As MASLabel = InfoCard(window, "No parallel dashboard", "The Showcase does not read manifests, parse reports, or build a second certification engine. It presents static commercial guidance through MASLabel, MASDataGrid, and PageHost layout builders.")

        Dim matrix As MASDataGrid = window.Controls.AddDataGrid()
        matrix.SelectionMode = MASDataGridSelectionMode.Row
        matrix.RowHeightDip = 32.0F
        matrix.HeaderHeightDip = 42.0F
        AddReadOnlyDataGridColumn(matrix, "proof", "Commercial proof", 230.0F)
        AddReadOnlyDataGridColumn(matrix, "owner", "Official owner", 250.0F)
        AddReadOnlyDataGridColumn(matrix, "responsibility", "Showcase responsibility", 430.0F)
        matrix.AddRow("Packaging gate", "Nexamas.UI eng/ci", "Show the result concept; do not call packaging internals.")
        matrix.AddRow("Quality manifest lock", "Nexamas.UI test harness", "Explain that tests are locked; do not enumerate internal test plans.")
        matrix.AddRow("Performance smoke", "Nexamas.UI benchmarks", "Reference the release proof without running benchmarks from the demo.")
        matrix.AddRow("Public API budget", "Nexamas.UI source-contract gate", "Keep the consumer project on public controls/facades only.")
        matrix.AddRow("Certification evidence", "Nexamas.UI internal certification", "Summarize commercial readiness without importing Friend-only hosts.")
        matrix.SelectedRowIndex = 0
        FitDataGridToRows(matrix)

        Dim action As MASButton = window.Controls.AddButton("Show release boundary")
        action.WithSize(MASSize.Compact)
        AddHandler action.Click,
            Sub()
                window.Services.Toasts.Info("Certification evidence is Nexamas.UI-owned; Showcase remains a clean external consumer.", "Public API boundary")
            End Sub

        Dim certificationBoundary As MASExpander = window.Controls.AddExpander("Developer certification boundary", expanded:=False, configure:=Sub(expander As MASExpander)
                                                                                                                                                  expander.WithSize(MASSize.FillWidth.OffsetHeight(300.0F))
                                                                                                                                                  expander.Add(intro)
                                                                                                                                                  expander.Add(boundaryCard)
                                                                                                                                                  expander.Add(releaseCard)
                                                                                                                                                  expander.Add(buyerCard)
                                                                                                                                                  expander.Add(noParallelCard)
                                                                                                                                              End Sub)

        AddShowcaseContent(page, status, MASSize.HugContent)
        AddShowcaseContent(page, matrix, MASSize.FillWidth)
        page.ActionGroup(Sub(actions As MASApplicationActionGroupLayoutBuilder)
                             actions.AlignCenter().Add(action, MASSize.[Default])
                         End Sub)
        AddShowcaseContent(page, certificationBoundary, MASSize.FillWidth)
    End Sub

    Private Shared Sub BuildApplicationArchitecture(page As MASApplicationLayoutPageBuilder,
                                                    window As MASApplicationWindow)
        Dim status As MASLabel = Heading(window, "Application architecture: PageHost + AppLayout + SplitView + MAS-owned surfaces")
        Dim intro As MASLabel = Body(window, "This page demonstrates Nexamas.UI as an application architecture, not a bag of controls. The active window owns the PageHost, the Shell, the services, the runtime size profile, and the semantic page-layout builders. Showcase declares intent only; Nexamas.UI resolves spacing, content width, split panes, filter rows, galleries, actions, responsive app-layout visuals, split workspace surfaces, and surfaces.")

        Dim pageKindLabel As MASLabel = Muted(window, "Page preset")
        Dim pageKindPicker As MASComboBox = window.Controls.AddComboBox(items:=New String() {"Standard", "Dashboard", "DenseData", "Editor", "Surface"}, selectedIndex:=1)
        pageKindPicker.WithSize(MASSize.Compact)

        Dim routeSearchLabel As MASLabel = Muted(window, "Architecture route search")
        Dim routeSearch As MASSearchTextBox = window.Controls.AddSearchTextBox("",
            Sub(box As MASSearchTextBox)
                box.Placeholder = "Search PageHost, SplitPane, Gallery, ActionGroup..."
                box.SetSuggestions(New String() {"PageHost", "ApplicationPage", "SplitPane", "FilterBar", "FormRow", "Gallery", "ActionGroup", "SurfaceLayout"})
                box.AddRecentSearch("PageHost")
                box.AddRecentSearch("ApplicationPage")
                box.AddFilterToken("owner", "ApplicationSystem")
            End Sub)
        routeSearch.WithSize(MASSize.Compact)

        Dim architectureMatrix As MASListView = window.Controls.AddListView(configure:=Sub(view As MASListView)
                                                                                view.WithDetailsView()
                                                                                view.StandaloneChrome()
                                                                                view.AddColumn("Architecture layer", 220.0F)
                                                                                view.AddColumn("Public route shown", 280.0F)
                                                                                view.AddColumn("What Nexamas.UI owns", 360.0F)
                                                                            End Sub)
        architectureMatrix.WithDefaultSize()
        PopulateApplicationArchitectureRows(architectureMatrix)

        Dim sampleName As MASTextBox = window.Controls.AddTextBox("New product page")
        sampleName.WithDefaultSize()
        Dim sampleToggle As MASToggleSwitch = window.Controls.AddToggleSwitch("Show navigation tree", checked:=True)
        sampleToggle.WithDefaultSize()

        Dim appLayoutStatus As MASLabel = Muted(window, "AppLayout: responsive visual app chrome only; Showcase does not create a router, PageHost owner, child-content host, or shell engine.")
        Dim appLayout As MASAppLayout = window.Controls.AddAppLayout("Responsive product shell", Sub(layout As MASAppLayout)
                                                                                                       layout.SetNavigation("Navigation", "NavigationRail, Drawer, and MenuBar can sit beside the workspace without becoming routers.")
                                                                                                       layout.SetContent("Workspace", "DataGrid, DashboardGrid, forms, and reports compose inside the official content slot.")
                                                                                                       layout.SetDetails("Details", "Preview, inspector, and status regions remain visual app-layout slots.")
                                                                                                       layout.ShowNavigation = True
                                                                                                       layout.ShowDetails = True
                                                                                                       layout.ShowStatusBar = True
                                                                                                       layout.WithSize(MASSize.FillWidth.OffsetHeight(330.0F))
                                                                                                   End Sub)

        Dim splitStatus As MASLabel = Muted(window, "SplitView: drag dividers visually resize panes; it does not become a dock engine, child-content host, router, or persistence path.")
        Dim splitView As MASSplitView = window.Controls.AddSplitView("Resizable workspace", Sub(split As MASSplitView)
                                                                                                 split.LeftPaneTitle = "Navigation"
                                                                                                 split.ContentPaneTitle = "Workspace"
                                                                                                 split.RightPaneTitle = "Inspector"
                                                                                                 split.SetPaneTexts("Rail, filters, and page sections live here.", "Dashboards, tables, forms, and charts live here.", "Preview and detail context live here.")
                                                                                                 split.LeftPaneRatio = 0.24F
                                                                                                 split.RightPaneRatio = 0.26F
                                                                                                 split.WithSize(MASSize.FillWidth.OffsetHeight(330.0F))
                                                                                             End Sub)
        AddHandler splitView.SplitViewChanged,
            Sub(sender As Object, e As EventArgs)
                splitStatus.Text = "SplitView: " & splitView.SummaryText
            End Sub

        Dim confirmAction As MASButton = window.Controls.AddButton("Show architecture toast").AsPrimary()
        Dim explainAction As MASButton = window.Controls.AddButton("Explain boundary")
        Dim clearAction As MASButton = window.Controls.AddButton("Clear floating UI")

        AddHandler pageKindPicker.SelectionChanged,
            Sub(sender As Object, e As EventArgs)
                status.Text = "Application architecture: selected preset " & If(pageKindPicker.SelectedIndex >= 0, pageKindPicker.SelectedIndex.ToString(CultureInfo.InvariantCulture), "none") & " is declared by the page; Nexamas.UI owns resolved padding, spacing, and content width."
            End Sub
        AddHandler routeSearch.SearchCommitted,
            Sub(sender As Object, e As EventArgs)
                window.Services.Toasts.Info("Architecture search committed: " & If(String.IsNullOrWhiteSpace(routeSearch.EffectiveSearchText), "empty", routeSearch.EffectiveSearchText), "Application architecture")
            End Sub
        AddHandler confirmAction.Click,
            Sub()
                window.Services.Toasts.Success("PageHost, ApplicationPage, SplitPane, FilterBar, FormRow, Gallery, and ActionGroup are visible on one MAS-owned application page.", "Application architecture")
            End Sub
        AddHandler explainAction.Click,
            Sub()
                window.Services.Dialogs.Information("Showcase does not assign Left, Top, Width, Height, or create a second layout engine. It declares semantic page intent and Nexamas.UI resolves the application surface.", "Layout ownership")
            End Sub
        AddHandler clearAction.Click,
            Sub()
                window.Services.Toasts.ClearAll()
                window.Services.Tooltips.Clear()
            End Sub

        AddShowcaseContent(page, status, MASSize.HugContent)
        AddShowcaseContent(page, intro, MASSize.FillWidth)
        page.FilterBar(Sub(filters As MASApplicationFilterBarLayoutBuilder)
                           filters.Wrap().Gap(MASLayoutSpacing.Medium).HugContent().Field(pageKindLabel, pageKindPicker, MASSize.Compact).Field(routeSearchLabel, routeSearch, MASSize.Compact)
                       End Sub)
        page.SplitPane(Sub(split As MASApplicationSplitPaneLayoutBuilder)
                           split.Gap(MASLayoutSpacing.Large).
                               AddNarrative(InfoCard(window, "One same-window PageHost", "The Showcase shell registers metadata in Window.Pages and swaps workspace content through the official PageHost instead of opening Forms or hidden panels."), MASSize.FillWidth).
                               AddNarrative(InfoCard(window, "ApplicationPage preset", "This architecture proof documents page.ApplicationPage(MASApplicationPageLayoutKind.Dashboard, window.Shell) as a public semantic route. The Showcase runtime now applies one full-width PageHost composition contract so every active route uses the same workspace width."), MASSize.FillWidth).
                               AddNarrative(InfoCard(window, "No coordinate layout", "The page uses semantic MAS layout builders only. It does not set Left, Top, Width, Height, Location, or SetBounds."), MASSize.FillWidth).
                               AddSurface(architectureMatrix, MASSize.FillWidth).
                               AddSurface(InfoCard(window, "Surface route boundary", "Application-surface layout routes belong to the host shell. Child PageHost pages demonstrate them as architecture facts and do not replace parent LayoutApplicationSurface from inside the page."), MASSize.FillWidth)
                       End Sub)
        AddShowcaseContent(page, Heading(window, "AppLayout + SplitView"), MASSize.HugContent)
        page.Grid(2).Gap(MASLayoutSpacing.Large).EqualItemSize().Add(appLayout, MASSize.FillWidth).Add(splitView, MASSize.FillWidth)
        page.Grid(2).Gap(MASLayoutSpacing.Large).EqualItemSize().Add(appLayoutStatus, MASSize.FillWidth).Add(splitStatus, MASSize.FillWidth)
        page.FormRow(Sub(row As MASApplicationFormRowLayoutBuilder)
                         row.Label(Muted(window, "FormRow sample")).Input(sampleName, MASSize.FillWidth).Add(sampleToggle, MASSize.[Default]).Gap(MASLayoutSpacing.Medium).Stretch()
                     End Sub)
        page.Gallery(Sub(gallery As MASApplicationGalleryLayoutBuilder)
                         gallery.PreviewTiles().Columns(3).Gap(MASLayoutSpacing.Medium).
                             Add(InfoCard(window, "SplitPane", "Narrative and surface panes are one MASLayout structure, not two manually sized panels."), MASSize.FillWidth).
                             Add(InfoCard(window, "FilterBar", "Search, combo, toggle, and compact field rows declare intent through MASApplicationFilterBarLayoutBuilder."), MASSize.FillWidth).
                             Add(InfoCard(window, "Gallery", "Responsive cards use semantic tile sizing and wrapping owned by MASApplicationGalleryLayoutBuilder."), MASSize.FillWidth)
                     End Sub)
        page.Flow().Gap(MASLayoutSpacing.Medium).EqualItemWidth().Add(InfoCard(window, "Stack / Flow", "Flow and stack builders keep related controls together without raw coordinates."), MASSize.[Default]).Add(InfoCard(window, "Size profile aware", "All layout builders resolve through MASSize/MASLayout and the active runtime size profile."), MASSize.[Default])
        AddNaturalActionGroup(page, confirmAction, explainAction, clearAction)
    End Sub

    Private Shared Sub BuildWorkflowFoundations(page As MASApplicationLayoutPageBuilder,
                                                window As MASApplicationWindow)
        Dim status As MASLabel = Heading(window, "Workflow foundations: actions, binding story, FormValidationSummary, and validation visuals")
        Dim intro As MASLabel = Body(window, "This page shows the public product-facing surfaces that surround Nexamas.UI workflow foundations. Command / Action, Data Binding, and Form Validation remain Nexamas.UI-owned foundation systems; the Showcase demonstrates safe consumer routes only: action groups, buttons, input values, validation visuals, FormValidationSummary, service feedback, and an explicit readiness matrix.")

        Dim boundaryCard As MASLabel = InfoCard(window, "Foundation boundary", "The internal workflow foundations are not opened as a public SDK engine. This page does not import registry, binder, form-session, rule, or snapshot contracts. It shows the visible surfaces that a product developer uses today.")
        Dim publicRoutesCard As MASLabel = InfoCard(window, "Public routes", "Actions flow through PageHost action groups and MASButton events; field feedback uses MASTextBox.SetValidation / ClearValidation; form-level feedback uses Window.Controls.AddFormValidationSummary(...); feedback uses Window.Services.Toasts and Dialogs.")

        Dim capabilityMatrix As MASListView = window.Controls.AddListView(configure:=Sub(view As MASListView)
                                                                              view.WithDetailsView()
                                                                              view.StandaloneChrome()
                                                                              view.AddColumn("Workflow area", 210.0F)
                                                                              view.AddColumn("Shown public route", 310.0F)
                                                                              view.AddColumn("Nexamas.UI-owned foundation", 430.0F)
                                                                          End Sub)
        PopulateWorkflowFoundationRows(capabilityMatrix)
        capabilityMatrix.WithSize(MatrixSizeForRows(5))

        Dim nameBox As MASTextBox = window.Controls.AddTextBox("Nexamas UI Showcase")
        nameBox.Placeholder = "Required display name"
        nameBox.ShowValidationIndicator = True
        nameBox.WithSize(MASSize.Large)

        Dim emailBox As MASTextBox = window.Controls.AddTextBox("demo@nexamas-ui.local")
        emailBox.Placeholder = "Required email-like contact"
        emailBox.ShowValidationIndicator = True
        emailBox.WithSize(MASSize.Large)

        Dim roleItems As String() = New String() {"Designer", "Developer", "Product owner", "Reviewer"}
        Dim rolePicker As MASComboBox = window.Controls.AddComboBox(items:=roleItems, selectedIndex:=1)
        rolePicker.WithSize(MASSize.Compact)

        Dim activeToggle As MASToggleSwitch = window.Controls.AddToggleSwitch("Workflow enabled", checked:=True)
        activeToggle.WithDefaultSize()

        Dim bindingPreview As MASLabel = Muted(window, "Binding preview: waiting for field changes.")
        Dim validationSummary As MASListView = window.Controls.AddListView(configure:=Sub(view As MASListView)
                                                                               view.WithDetailsView()
                                                                               view.StandaloneChrome()
                                                                               view.AddColumn("Field", 190.0F)
                                                                               view.AddColumn("Current value", 260.0F)
                                                                               view.AddColumn("Public validation state", 260.0F)
                                                                           End Sub)
        validationSummary.WithSize(MatrixSizeForRows(3))

        Dim formValidationOverview As MASFormValidationSummary = window.Controls.AddFormValidationSummary("Workflow validation summary", Sub(summary As MASFormValidationSummary)
                                                                                                                                             summary.AddMessage("Name", "Display name is required before submit.", MASTextValidationState.Error)
                                                                                                                                             summary.AddMessage("Contact", "Contact must contain @ for this public visual demo.", MASTextValidationState.Warning)
                                                                                                                                             summary.AddMessage("Role", "Role selection is ready.", MASTextValidationState.Success)
                                                                                                                                             summary.WithSize(MASSize.FillWidth.OffsetHeight(190.0F))
                                                                                                                                         End Sub)

        Dim validateAction As MASButton = window.Controls.AddButton("Validate fields").AsPrimary()
        Dim submitAction As MASButton = window.Controls.AddButton("Submit workflow")
        Dim clearAction As MASButton = window.Controls.AddButton("Clear validation")

        Dim workflowStepper As MASStepper = window.Controls.AddStepper(MASStepperOrientation.Horizontal, Sub(stepper As MASStepper)
                                                                                                             stepper.AddStep("Collect")
                                                                                                             stepper.AddStep("Validate")
                                                                                                             stepper.AddStep("Submit")
                                                                                                             stepper.SetStepState(0, MASStepperStepState.Completed)
                                                                                                             stepper.SetStepState(1, MASStepperStepState.Current)
                                                                                                             stepper.SetStepState(2, MASStepperStepState.Pending)
                                                                                                             stepper.WithCurrentStep(1)
                                                                                                             stepper.WithSize(MASSize.FillWidth.OffsetHeight(112.0F))
                                                                                                         End Sub)
        Dim workflowWizard As MASWizard = window.Controls.AddWizard(MASStepperOrientation.Horizontal, Sub(wizard As MASWizard)
                                                                                                         wizard.AddStep("Collect", "Public inputs", MASLabel.Create(ResolveWorkflowFoundationWizardStepText(0)))
                                                                                                         wizard.AddStep("Validate", "Visual rules", MASLabel.Create(ResolveWorkflowFoundationWizardStepText(1)))
                                                                                                         wizard.AddStep("Submit", "Action route", MASLabel.Create(ResolveWorkflowFoundationWizardStepText(2)))
                                                                                                         wizard.WithCurrentStep(1)
                                                                                                         wizard.WithSize(MASSize.HugContent)
                                                                                                     End Sub)
        Dim previousStepAction As MASButton = window.Controls.AddButton("Previous step")
        Dim nextStepAction As MASButton = window.Controls.AddButton("Next step").AsPrimary()
        Dim workflowStepSummary As MASLabel = Muted(window, ResolveWorkflowFoundationWizardStepText(workflowWizard.CurrentIndex))

        Dim resolveRole As Func(Of String) =
            Function()
                If rolePicker.SelectedIndex >= 0 AndAlso rolePicker.SelectedIndex < roleItems.Length Then
                    Return roleItems(rolePicker.SelectedIndex)
                End If
                Return "Unassigned"
            End Function

        Dim updateBindingPreview As Action =
            Sub()
                bindingPreview.Text = "Binding preview: Name='" & If(nameBox.Text, String.Empty) & "' | Contact='" & If(emailBox.Text, String.Empty) & "' | Role='" & resolveRole.Invoke() & "' | Enabled='" & activeToggle.Checked.ToString() & "'."
                RefreshWorkflowEvidenceRows(validationSummary, nameBox.Text, emailBox.Text, resolveRole.Invoke(), "Preview")
            End Sub

        Dim applyValidation As Action =
            Sub()
                Dim nameText As String = If(nameBox.Text, String.Empty).Trim()
                Dim emailText As String = If(emailBox.Text, String.Empty).Trim()
                Dim validName As Boolean = nameText.Length >= 3
                Dim validEmail As Boolean = emailText.Contains("@") AndAlso emailText.Contains(".")

                If validName Then
                    nameBox.SetValidation(MASTextValidationState.Success, "Name is ready.")
                Else
                    nameBox.SetValidation(MASTextValidationState.[Error], "Name must contain at least three characters.")
                End If

                If validEmail Then
                    emailBox.SetValidation(MASTextValidationState.Success, "Contact field is ready.")
                Else
                    emailBox.SetValidation(MASTextValidationState.[Error], "Enter an email-like value for the demo workflow.")
                End If

                Dim resultText As String = If(validName AndAlso validEmail, "Valid", "Needs review")
                status.Text = "Workflow foundations: public validation visuals are " & resultText & "."
                RefreshWorkflowEvidenceRows(validationSummary, nameBox.Text, emailBox.Text, resolveRole.Invoke(), resultText)
                formValidationOverview.ClearMessages()
                formValidationOverview.AddMessage("Name", If(validName, "Display name is ready.", "Display name must contain at least three characters."), If(validName, MASTextValidationState.Success, MASTextValidationState.Error))
                formValidationOverview.AddMessage("Contact", If(validEmail, "Contact value is ready.", "Contact must contain an email-like value."), If(validEmail, MASTextValidationState.Success, MASTextValidationState.Error))
                formValidationOverview.AddMessage("Role", "Role selected: " & resolveRole.Invoke(), MASTextValidationState.Information)
                window.Refresh()
            End Sub

        AddHandler nameBox.TextChanged, Sub(sender As Object, e As EventArgs) updateBindingPreview.Invoke()
        AddHandler emailBox.TextChanged, Sub(sender As Object, e As EventArgs) updateBindingPreview.Invoke()
        AddHandler rolePicker.SelectionChanged, Sub(sender As Object, e As EventArgs) updateBindingPreview.Invoke()

        AddHandler validateAction.Click,
            Sub()
                applyValidation.Invoke()
                window.Services.Toasts.Info("Validation visuals were applied through MASTextBox.SetValidation.", "Workflow foundations")
            End Sub
        AddHandler submitAction.Click,
            Sub()
                applyValidation.Invoke()
                If nameBox.ValidationState = MASTextValidationState.Success AndAlso emailBox.ValidationState = MASTextValidationState.Success Then
                    window.Services.Toasts.Success("Workflow submitted through the public action surface. Foundation ownership remains inside Nexamas.UI.", "Workflow foundations")
                Else
                    window.Services.Dialogs.Error(message:="The workflow is not ready to submit.", title:="Workflow foundations", detail:="Fix the public validation states first. The Showcase is not using the internal FormValidation foundation directly.", ownerKey:="showcase.workflow.validation")
                End If
            End Sub
        AddHandler clearAction.Click,
            Sub()
                nameBox.ClearValidation()
                emailBox.ClearValidation()
                formValidationOverview.ClearMessages()
                formValidationOverview.AddMessage("Validation", "Public field validation visuals were cleared.", MASTextValidationState.Information)
                status.Text = "Workflow foundations: validation visuals cleared."
                updateBindingPreview.Invoke()
                window.Refresh()
            End Sub
        AddHandler previousStepAction.Click,
            Sub()
                workflowStepper.MovePrevious()
                workflowWizard.MovePrevious()
                workflowStepSummary.Text = ResolveWorkflowFoundationWizardStepText(workflowWizard.CurrentIndex)
                status.Text = "Stepper / Wizard: moved to step " & (workflowWizard.CurrentIndex + 1).ToString(CultureInfo.InvariantCulture) & " of " & workflowWizard.StepCount.ToString(CultureInfo.InvariantCulture) & "."
                window.Refresh()
            End Sub
        AddHandler nextStepAction.Click,
            Sub()
                workflowStepper.MoveNext()
                workflowWizard.MoveNext()
                workflowStepSummary.Text = ResolveWorkflowFoundationWizardStepText(workflowWizard.CurrentIndex)
                status.Text = "Stepper / Wizard: moved to step " & (workflowWizard.CurrentIndex + 1).ToString(CultureInfo.InvariantCulture) & " of " & workflowWizard.StepCount.ToString(CultureInfo.InvariantCulture) & "."
                window.Refresh()
            End Sub

        updateBindingPreview.Invoke()

        AddShowcaseContent(page, status, MASSize.HugContent)
        AddShowcaseContent(page, intro, MASSize.FillWidth)
        page.Grid(2).Gap(MASLayoutSpacing.Large).EqualItemSize().Add(boundaryCard, MASSize.FillWidth).Add(publicRoutesCard, MASSize.FillWidth)

        Dim nameLabel As MASLabel = Muted(window, "Name")
        Dim contactLabel As MASLabel = Muted(window, "Contact")
        page.Flow().Gap(MASLayoutSpacing.Medium).IntrinsicItemSize().
            Add(nameLabel, MASSize.HugContent).
            Add(nameBox, MASSize.Large).
            Add(contactLabel, MASSize.HugContent).
            Add(emailBox, MASSize.Large)

        Dim roleLabel As MASLabel = Muted(window, "Role")
        page.Flow().Gap(MASLayoutSpacing.Medium).IntrinsicItemSize().
            Add(roleLabel, MASSize.HugContent).
            Add(rolePicker, MASSize.Compact).
            Add(activeToggle, MASSize.[Default])

        AddShowcaseContent(page, bindingPreview, MASSize.HugContent)
        page.ActionGroup(Sub(actions As MASApplicationActionGroupLayoutBuilder)
                             actions.Gap(MASLayoutSpacing.Medium).AlignCenter()
                             actions.Add(validateAction, MASSize.Large)
                             actions.Add(submitAction, MASSize.Large)
                             actions.Add(clearAction, MASSize.Large)
                         End Sub)

        AddShowcaseContent(page, Heading(window, "Validation state"), MASSize.HugContent)
        page.Grid(2).Gap(MASLayoutSpacing.Large).EqualItemSize().Add(formValidationOverview, MASSize.FillWidth).Add(validationSummary, MASSize.FillWidth)

        AddShowcaseContent(page, Heading(window, "Wizard flow"), MASSize.HugContent)
        workflowStepper.WithSize(MASSize.FillWidth.OffsetHeight(112.0F))
        page.Add(workflowStepper, MASSize.FillWidth.OffsetHeight(112.0F))
        AddShowcaseContent(page, workflowStepSummary, MASSize.FillWidth)
        page.ActionGroup(Sub(actions As MASApplicationActionGroupLayoutBuilder)
                             actions.Gap(MASLayoutSpacing.Medium).AlignCenter()
                             actions.Add(previousStepAction, MASSize.Large)
                             actions.Add(nextStepAction, MASSize.Large)
                         End Sub)

        AddShowcaseContent(page, Heading(window, "Workflow foundation matrix"), MASSize.HugContent)
        AddShowcaseContent(page, capabilityMatrix, MASSize.FillWidth)
    End Sub

    Private Shared Sub BuildCommercialFoundationDecisions(page As MASApplicationLayoutPageBuilder,
                                                         window As MASApplicationWindow)
        Dim status As MASLabel = Heading(window, "Commercial foundations: Report / Print and Plugin / Module decisions")
        Dim intro As MASLabel = Body(window, "This page makes two important Nexamas.UI foundations visible without pretending they are public runtime hosts. Report / Print and Plugin / Module are certified Friend-owned foundations today. The Showcase presents their product value, boundaries, gates, and next-host decisions through normal MAS controls only.")

        Dim reportCard As MASLabel = InfoCard(window, "Report / Print foundation", "Nexamas.UI owns a report document, table, preview-snapshot, and printable-page planning model internally. There is no public print command, PDF exporter, report designer, or Showcase-owned reporting engine in this phase.")
        Dim pluginCard As MASLabel = InfoCard(window, "Plugin / Module foundation", "Nexamas.UI owns module descriptors, contributions, registry snapshots, and readiness status internally. There is no external plugin loader, dynamic assembly loading, or demo-owned extension host in this phase.")
        Dim decisionCard As MASLabel = InfoCard(window, "Capability decision", "Both systems are visible as certified commercial foundations. A future public host must consume the Nexamas.UI-owned foundation facts instead of creating wrappers, adapters, bridges, or parallel paths.")
        Dim certificationCard As MASLabel = InfoCard(window, "Certification route", "The Certification Center and Showcase Coverage Gate now record these foundations as intentional capability decisions. This page explains the decision; it does not run foundation gates or read reports.")

        Dim foundationMatrix As MASListView = window.Controls.AddListView(configure:=Sub(view As MASListView)
                                                                              view.WithDetailsView()
                                                                              view.StandaloneChrome()
                                                                              view.AddColumn("Foundation", 210.0F)
                                                                              view.AddColumn("Product-facing decision", 330.0F)
                                                                              view.AddColumn("Boundary kept closed", 430.0F)
                                                                          End Sub)
        foundationMatrix.WithDefaultSize()
        PopulateCommercialFoundationRows(foundationMatrix)

        Dim nextStepMatrix As MASListView = window.Controls.AddListView(configure:=Sub(view As MASListView)
                                                                            view.WithDetailsView()
                                                                            view.StandaloneChrome()
                                                                            view.AddColumn("Future host", 210.0F)
                                                                            view.AddColumn("Allowed direction", 360.0F)
                                                                            view.AddColumn("Forbidden shortcut", 400.0F)
                                                                        End Sub)
        nextStepMatrix.WithDefaultSize()
        PopulateCommercialFoundationHostRows(nextStepMatrix)

        Dim acknowledgeAction As MASButton = window.Controls.AddButton("Explain decision").AsPrimary()
        Dim certificationAction As MASButton = window.Controls.AddButton("Certification route")
        Dim boundaryAction As MASButton = window.Controls.AddButton("Boundary reminder")

        AddHandler acknowledgeAction.Click,
            Sub()
                status.Text = "Commercial foundations: visible as capability decisions, not opened as runtime hosts."
                window.Services.Toasts.Info("Report / Print and Plugin / Module are intentionally shown as certified foundation decisions.", "Commercial foundations")
                window.Refresh()
            End Sub
        AddHandler certificationAction.Click,
            Sub()
                window.Services.Toasts.Success("Certification Center records these foundations through Nexamas.UI-owned evidence entries.", "Commercial foundations")
            End Sub
        AddHandler boundaryAction.Click,
            Sub()
                window.Services.Dialogs.Information(message:="This Showcase page does not import ReportPrintSystem or PluginModuleSystem internals, does not execute print/export/plugin loading, and does not create a parallel host.", title:="Foundation boundary", ownerKey:="showcase.commercial.foundations")
            End Sub

        AddShowcaseContent(page, status, MASSize.HugContent)
        AddShowcaseContent(page, intro, MASSize.FillWidth)
        page.Grid(2).Gap(MASLayoutSpacing.Large).EqualItemSize().Add(reportCard, MASSize.FillWidth).Add(pluginCard, MASSize.FillWidth).Add(decisionCard, MASSize.FillWidth).Add(certificationCard, MASSize.FillWidth)
        AddShowcaseContent(page, foundationMatrix, MASSize.FillWidth)
        AddShowcaseContent(page, nextStepMatrix, MASSize.FillWidth)
        AddNaturalActionGroup(page, acknowledgeAction, certificationAction, boundaryAction)
    End Sub

    Private Shared Sub BuildElementCoverage(page As MASApplicationLayoutPageBuilder,
                                            window As MASApplicationWindow)
        Dim title As MASTitle = window.Controls.AddTitle("Official Element Coverage")
        title.DrawDivider = True

        Dim status As MASLabel = Heading(window, "Every official Nexamas.UI element now has a visible Showcase coverage decision")
        Dim intro As MASLabel = Body(window, "This page is the Showcase inventory surface for public elements. It makes the coverage map explicit so a control cannot remain hidden inside a broad page or be forgotten after a new Nexamas.UI stage. Live control samples still remain on their product pages; this matrix tells you exactly where to inspect each family and which routes are certification-only, service-owned, or host-owned.")

        Dim addTitleProof As MASLabel = InfoCard(window,
            "MASTitle live proof",
            "The page heading above is created by Window.Controls.AddTitle(...), so the title gateway is no longer only metadata/infrastructure coverage.")
        Dim publicGatewayProof As MASLabel = InfoCard(window,
            "Public gateway proof",
            "Window.Controls.Add... gateways are mapped to active PageHost routes. Generic infrastructure, service façades, and shell-owned surfaces are documented explicitly instead of being silently skipped.")
        Dim shellBoundaryProof As MASLabel = InfoCard(window,
            "Shell menu trigger / MASMenuButton",
            "MASMenuButton remains a shell-owned menu trigger route. Context/dropdown menu builders stay on their official shell or service routes; Showcase does not insert native host controls into MAS PageHost content slots.")

        Dim view As MASDataGrid = window.Controls.AddDataGrid()
        view.SelectionMode = MASDataGridSelectionMode.Row
        view.RowHeightDip = 32.0F
        view.HeaderHeightDip = 42.0F
        AddReadOnlyDataGridColumn(view, "element", "Element / gateway", 250.0F)
        AddReadOnlyDataGridColumn(view, "route", "Active Showcase route", 230.0F)
        AddReadOnlyDataGridColumn(view, "decision", "Coverage decision", 520.0F)
        PopulateElementCoverageRows(view)
        FitDataGridToRows(view)

        Dim verify As MASButton = window.Controls.AddButton("Show coverage toast").AsPrimary()
        AddHandler verify.Click,
            Sub(sender As Object, e As EventArgs)
                window.Services.Toasts.Success("Element Coverage confirms AddTitle plus public gateway coverage mapping.", "Showcase coverage")
            End Sub

        Dim elementCoverageBoundary As MASExpander = window.Controls.AddExpander("Developer element coverage boundary", expanded:=False, configure:=Sub(expander As MASExpander)
                                                                                                                                                       expander.WithSize(MASSize.FillWidth.OffsetHeight(260.0F))
                                                                                                                                                       expander.Add(intro)
                                                                                                                                                       expander.Add(addTitleProof)
                                                                                                                                                       expander.Add(publicGatewayProof)
                                                                                                                                                       expander.Add(shellBoundaryProof)
                                                                                                                                                   End Sub)

        AddShowcaseContent(page, title, MASSize.HugContent)
        AddShowcaseContent(page, status, MASSize.HugContent)
        AddShowcaseContent(page, view, MASSize.FillWidth)
        AddNaturalActionGroup(page, verify)
        AddShowcaseContent(page, elementCoverageBoundary, MASSize.FillWidth)
    End Sub

End Class
