Option Strict On
Option Explicit On

Imports System
Imports System.Diagnostics
Imports System.Globalization
Imports Nexamas.UI.Application
Imports Nexamas.UI.Components
Imports Nexamas.UI.Controls
Imports Nexamas.UI.Layout
Imports Nexamas.UI.Presentation

Namespace Nexamas.UI.Certification

    ''' <summary>
    ''' Nexamas UI-owned internal certification center surface.
    ''' </summary>
    ''' <remarks>
    ''' The center consumes NexamasUICertification.CreateManifest only. It does not run gates,
    ''' read gate scripts, read markdown reports, execute captures, create diagnostics scanners,
    ''' or let demo code own certification logic.
    ''' </remarks>
    Friend NotInheritable Class NexamasUICertificationCenterPage
        Implements IDisposable

        Private Const DialogOwnerKey As String = "MAS.Certification.Center"

        Private _window As MASApplicationWindow
        Private _title As MASTitle
        Private _description As MASLabel
        Private _status As MASLabel
        Private _summary As MASLabel
        Private _readiness As MASLabel
        Private _systems As MASListView
        Private _details As MASLabel
        Private _developerNote As MASLabel
        Private _refresh As MASButton
        Private _manifest As NexamasUICertificationManifest
        Private _disposed As Boolean

        Friend Sub Build(window As MASApplicationWindow)
            If window Is Nothing Then Throw New ArgumentNullException(NameOf(window))

            _window = window
            CreateControls(includeHeader:=True)
            LayoutControls()
            RefreshManifestSafely(showDialogOnFailure:=True)
        End Sub

        Friend Sub Build(window As MASApplicationWindow, page As MASApplicationLayoutPageBuilder)
            If window Is Nothing Then Throw New ArgumentNullException(NameOf(window))
            If page Is Nothing Then Throw New ArgumentNullException(NameOf(page))

            _window = window
            CreateControls(includeHeader:=False)
            LayoutControls(page, includeHeader:=False)
            RefreshManifestSafely(showDialogOnFailure:=True)
        End Sub

        Private Sub Dispose() Implements IDisposable.Dispose
            If _disposed Then Return
            _disposed = True

            If _systems IsNot Nothing Then RemoveHandler _systems.SelectedIndexChanged, AddressOf HandleSelectionChanged
            If _refresh IsNot Nothing Then RemoveHandler _refresh.Click, AddressOf HandleRefresh

            _manifest = Nothing
            _window = Nothing
        End Sub

        Private Sub CreateControls(includeHeader As Boolean)
            If includeHeader Then
                _title = _window.Controls.AddTitle("Nexamas UI Certification Center")
                _title.WithDefaultSize()
            End If

            _description = _window.Controls.AddLabel(
                "Commercial readiness in plain language: this Nexamas UI-owned page says what is ready, why it matters, and which Nexamas UI system owns the proof. The demo only hosts this page; it does not run tests, read reports, or rebuild evidence.",
                configure:=Sub(label As MASLabel)
                               label.LabelVariant = MASLabelVariant.Body
                               label.TextRole = MASLabelTextRole.Secondary
                               label.MultiLine = True
                               label.WordWrap = True
                           End Sub)
            _description.WithDefaultSize()

            _status = _window.Controls.AddLabel("Commercial status: loading...",
                configure:=Sub(label As MASLabel)
                               label.LabelVariant = MASLabelVariant.Heading
                               label.TextRole = MASLabelTextRole.Primary
                               label.MultiLine = True
                               label.WordWrap = True
                           End Sub)
            _status.WithDefaultSize()

            _summary = _window.Controls.AddLabel("Loading the certification summary...",
                configure:=Sub(label As MASLabel)
                               label.LabelVariant = MASLabelVariant.Body
                               label.TextRole = MASLabelTextRole.Primary
                               label.MultiLine = True
                               label.WordWrap = True
                           End Sub)
            _summary.WithDefaultSize()

            _readiness = _window.Controls.AddLabel("Loading the certification areas...",
                configure:=Sub(label As MASLabel)
                               label.LabelVariant = MASLabelVariant.Body
                               label.TextRole = MASLabelTextRole.Secondary
                               label.MultiLine = True
                               label.WordWrap = True
                           End Sub)
            _readiness.WithDefaultSize()

            _systems = _window.Controls.AddListView(configure:=Sub(view As MASListView)
                                                                   view.WithDetailsView()
                                                                   view.StandaloneChrome()
                                                                   view.AddColumn("Certification area", 210.0F)
                                                                   view.AddColumn("Status", 100.0F)
                                                                   view.AddColumn("Customer value", 620.0F)
                                                               End Sub)
            _systems.WithDefaultSize()
            AddHandler _systems.SelectedIndexChanged, AddressOf HandleSelectionChanged

            _details = _window.Controls.AddLabel("Select an area to see the simple customer message and the internal owner that protects it.",
                configure:=Sub(label As MASLabel)
                               label.LabelVariant = MASLabelVariant.Body
                               label.TextRole = MASLabelTextRole.Secondary
                               label.MultiLine = True
                               label.WordWrap = True
                           End Sub)
            _details.WithDefaultSize()

            _developerNote = _window.Controls.AddLabel("Internal proof remains available through gates and reports, but this page is intentionally product-readable. Core Showcase capability rows: Application Ownership, Chart, PropertyGrid, Advanced SearchBox, Surface Materials, Services, Diagnostics Dashboard, Application Architecture, Workflow Foundations, Report / Print, and Plugin / Module. Localization / RTL is hosted through the dedicated MASLocalizationRtl page. It is rendered with MAS controls, MAS layout, MAS size intents, and PresentationSystem page slots.",
                configure:=Sub(label As MASLabel)
                               label.LabelVariant = MASLabelVariant.Caption
                               label.TextRole = MASLabelTextRole.Muted
                               label.MultiLine = True
                               label.WordWrap = True
                           End Sub)
            _developerNote.WithDefaultSize()

            _refresh = _window.Controls.AddButton("Refresh status")
            _refresh.WithDefaultSize()
            AddHandler _refresh.Click, AddressOf HandleRefresh
        End Sub

        Private Sub LayoutControls()
            _window.Controls.LayoutPage(
                Sub(page As MASApplicationLayoutPageBuilder)
                    LayoutControls(page, includeHeader:=True)
                End Sub)
        End Sub

        Private Sub LayoutControls(page As MASApplicationLayoutPageBuilder, includeHeader As Boolean)
            If page Is Nothing Then Throw New ArgumentNullException(NameOf(page))

            Dim presentation As MASPresentationPageBuilder = MASPresentationPage.Begin(page, MASApplicationPageLayoutKind.Dashboard, _window.Shell)
            If includeHeader AndAlso _title IsNot Nothing Then
                presentation.Header(_title, _description)
            Else
                presentation.FullWidth(_description, MASSize.FillWidth)
            End If
            presentation.SectionIntro(_status, _summary)
            presentation.FullWidth(_readiness, MASSize.FillWidth)
            presentation.DataGridSurface(_systems)
            presentation.FullWidth(_details, MASSize.FillWidth)
            presentation.FullWidth(_developerNote, MASSize.HugContent)
            presentation.Actions(
                Sub(actions As MASApplicationActionGroupLayoutBuilder)
                    actions.Gap(MASLayoutSpacing.Medium).AlignCenter()
                    actions.Add(_refresh, MASSize.[Default])
                End Sub)
        End Sub

        Private Sub HandleRefresh(sender As Object, e As EventArgs)
            RefreshManifestSafely(showDialogOnFailure:=True)
        End Sub

        Private Sub HandleSelectionChanged(sender As Object, e As EventArgs)
            Try
                UpdateDetailsFromSelection()
            Catch ex As Exception
                ShowPageError("The selected certification details could not be displayed.", ex)
            End Try
        End Sub

        Private Sub RefreshManifestSafely(showDialogOnFailure As Boolean)
            Try
                RefreshManifest()
            Catch ex As Exception
                SetUnavailableState("The certification summary could not be refreshed.", ex)
                If showDialogOnFailure Then ShowPageError("The certification summary could not be refreshed.", ex)
            End Try
        End Sub

        Private Sub RefreshManifest()
            _manifest = NexamasUICertification.CreateManifest()
            PopulateRows()
            UpdateSummary()
            SelectFirstRowIfNeeded()
        End Sub

        Private Sub PopulateRows()
            If _systems Is Nothing Then Return

            _systems.ClearItems()
            If _manifest Is Nothing Then Return

            For Each entry As NexamasUICertificationEntry In _manifest.Entries
                If entry Is Nothing Then Continue For

                Dim item As MASListViewItem = MASListViewItem.Create(ResolveAreaText(entry)).WithSubItems(New String() {
                    ResolveStatusText(entry.Status),
                    ResolveProofText(entry)
                })
                item.Tag = entry
                _systems.Add(item)
            Next
        End Sub

        Private Sub UpdateSummary()
            If _manifest Is Nothing Then
                SetUnavailableState("No Nexamas UI certification manifest is available.", Nothing)
                Return
            End If

            _status.Text = "Commercial readiness: " & ResolveMainStatusText(_manifest.Status) & " — " & ResolveProofMatrixHeadline(_manifest.ProofMatrix)
            _summary.Text = BuildExecutiveSummary(_manifest)
            If _readiness IsNot Nothing Then _readiness.Text = BuildPlainReadinessNarrative(_manifest)
        End Sub

        Private Sub SelectFirstRowIfNeeded()
            If _systems Is Nothing OrElse _manifest Is Nothing OrElse _manifest.Entries.Count = 0 Then
                If _details IsNot Nothing Then _details.Text = "No certification entries are available."
                Return
            End If

            If _systems.SelectedIndex < 0 Then
                _systems.SelectedIndex = 0
            Else
                UpdateDetailsFromSelection()
            End If
        End Sub

        Private Sub UpdateDetailsFromSelection()
            If _systems Is Nothing Then Return
            Dim selected As MASListViewItem = _systems.SelectedItem
            Dim entry As NexamasUICertificationEntry = If(selected Is Nothing, Nothing, TryCast(selected.Tag, NexamasUICertificationEntry))
            If entry Is Nothing Then
                _details.Text = "Select an area to see the simple customer message and the internal owner that protects it."
                Return
            End If

            _details.Text = ResolveAreaText(entry) & ": " & ResolvePlainMeaning(entry) & Environment.NewLine & Environment.NewLine &
                "Nexamas UI owner: " & ResolveOwnerText(entry) & ". The detailed gate/report names remain internal proof, not the main demo message."
        End Sub

        Private Sub SetUnavailableState(message As String, ex As Exception)
            If _status IsNot Nothing Then _status.Text = "Commercial status: unavailable"
            If _summary IsNot Nothing Then
                Dim detail As String = If(ex Is Nothing, String.Empty, " Details: " & ex.Message)
                _summary.Text = If(message, "The certification summary is unavailable.") & detail
            End If
            If _readiness IsNot Nothing Then _readiness.Text = "Certification areas could not be listed because the manifest is unavailable."
            If _details IsNot Nothing Then _details.Text = "The Certification Center kept ownership inside Nexamas UI and did not fall back to demo-owned evidence logic."
        End Sub

        Private Sub ShowPageError(message As String, ex As Exception)
            Try
                If _window IsNot Nothing AndAlso Not _window.IsDisposed AndAlso _window.Services IsNot Nothing Then
                    _window.Services.Dialogs.Error(
                        message:=If(message, "The Certification Center could not complete the requested action."),
                        title:="Nexamas UI Certification Center",
                        detail:=If(ex Is Nothing, String.Empty, ex.Message),
                        ownerKey:=DialogOwnerKey)
                End If
            Catch dialogException As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowDiagnosticOnly(dialogException, "Certification.Center.DialogBoundary")
            End Try
        End Sub

        Private Shared Function ResolveProofMatrixHeadline(proofMatrix As MASCertificationProofMatrix) As String
            If proofMatrix Is Nothing Then Return "proof scope unavailable"
            Return "source=" & proofMatrix.SourceStatus.ToString() &
                ", runtime=" & proofMatrix.RuntimeStatus.ToString() &
                ", package=" & proofMatrix.PackageStatus.ToString() &
                ", consumer=" & proofMatrix.ConsumerStatus.ToString()
        End Function

        Private Shared Function BuildExecutiveSummary(manifest As NexamasUICertificationManifest) As String
            If manifest Is Nothing Then Return "No certification data is available."

            Dim declaredCount As Integer = CountEntriesByStatus(manifest, NexamasUICertificationStatus.EvidenceDeclared)
            Dim baseCounts As String = manifest.CertifiedEntryCount.ToString(CultureInfo.InvariantCulture) & " of " &
                manifest.Entries.Count.ToString(CultureInfo.InvariantCulture) & " certification areas are gate-certified"
            If declaredCount > 0 Then
                baseCounts &= ", and " & declaredCount.ToString(CultureInfo.InvariantCulture) & " area(s) are declared evidence under monitoring"
            End If
            If manifest.ProofMatrix IsNot Nothing Then
                baseCounts &= ". " & manifest.ProofMatrix.Summary
            End If

            Select Case manifest.Status
                Case NexamasUICertificationStatus.Certified
                    Return "Nexamas UI is ready to demonstrate because " & baseCounts & ". It proves performance discipline, Performance/Diagnostics orchestration, visual proof, component registry coverage, Size/Layout runtime verification, large-data readiness, a commercial DataGrid, governed floating UI, frozen SDK contract, Certification Orchestration closure, and active Showcase coverage. The SDK harness baseline remains " &
                        manifest.ExpectedSdkHarnessCount.ToString(CultureInfo.InvariantCulture) &
                        " tests, and the demo is only a host for the official Nexamas UI page."
                Case NexamasUICertificationStatus.CertifiedWithMonitoring
                    Return "Nexamas UI can be demonstrated with warnings, not as a fully clean certificate, because " & baseCounts & ". Declared-only rows must stay visibly monitored until the Quality Orchestrator produces direct gate evidence for them. The SDK harness baseline remains " &
                        manifest.ExpectedSdkHarnessCount.ToString(CultureInfo.InvariantCulture) & " tests."
                Case NexamasUICertificationStatus.SourceCertifiedOnly
                    Return "Nexamas UI has source/governance proof only, not a full release certificate, because " & baseCounts & ". Runtime, package, and packed-consumer proof must come from the full quality runner before this can be marketed as fully certified."
                Case NexamasUICertificationStatus.Blocked
                    Return "Nexamas UI is not certified for demonstration because at least one evidence area is blocked. " & baseCounts & ". Fix the blocking gate/result before using this page as a clean certificate."
                Case Else
                    Return "Nexamas UI certification is incomplete because the evidence surface or governance chain is not fully registered. " & baseCounts & "."
            End Select
        End Function

        Private Shared Function CountEntriesByStatus(manifest As NexamasUICertificationManifest,
                                                     status As NexamasUICertificationStatus) As Integer
            If manifest Is Nothing OrElse manifest.Entries Is Nothing Then Return 0
            Dim count As Integer = 0
            For Each entry As NexamasUICertificationEntry In manifest.Entries
                If entry IsNot Nothing AndAlso entry.Status = status Then count += 1
            Next
            Return count
        End Function

        Private Shared Function BuildPlainReadinessNarrative(manifest As NexamasUICertificationManifest) As String
            If manifest Is Nothing Then Return "No certification areas are available."

            Dim lines As New List(Of String) From {
                "What the page proves:",
                "✓ Quality Orchestrator: lightweight gates now aggregate through one Nexamas UI-owned evidence route.",
                "✓ Asset presence: required docs, scripts, samples, CI, packaging, and project assets are guarded before evidence is trusted.",
                "✓ Component coverage: every registered component descriptor must resolve to direct render, family render, or named contract/system proof evidence.",
                "✓ Render coverage graph: target catalog scenarios, capture scenes, and component coverage entries must match exactly.",
                "✓ Size/Layout runtime: responsive modes, runtime profiles, DPI conversion, tiny bounds, and hit/visual overflow contracts are probed through one gate.",
                "✓ Performance/Diagnostics orchestration: budgets, immutable snapshots, dashboard availability truth, layout/render refresh counters, virtualization bridge, and release certification are checked together.",
                "✓ Certification closure: the Certification Manifest must own every Quality Orchestrator gate before commercial status can be trusted.",
                "✓ Performance: the platform has budgets and regression protection instead of guesswork.",
                "✓ Visual proof: important screens have render-verification evidence instead of manual screenshots.",
                "✓ Large data: 100k-style list/data scenarios use the shared virtualization system.",
                "✓ DataGrid: columns, rows, editing, summaries, pinned/wide columns, and virtualization ownership are closed.",
                "✓ Floating UI: dialogs, menus, tooltips, toasts, and overlays are governed by FloatRuntime.",
                "✓ SDK API: the public contract is frozen, documented, and protected.",
                "✓ Business controls: Chart Dashboard and PropertyGrid Inspector are visible through public PageHost routes.",
                "✓ Search + Data: Advanced SearchBox is demonstrated with DataGrid binding and filter-token flow.",
                "✓ Surface materials: eligible broad surfaces update live through public surface-material gateways.",
                "✓ Services: dialogs, toasts, tooltips, context menus, progress, file picker, and file explorer are shown through Window.Services.",
                "✓ Diagnostics: read-only dashboard rows are visible through the Nexamas UI-owned AttachDashboard host route without telemetry ownership in Showcase.",
                "✓ Application architecture: PageHost, ApplicationPage, SplitPane, FilterBar, FormRow, Gallery, Flow, and ActionGroup are visible as one product-facing architecture page.",
                "✓ Workflow foundations: Command / Action, Binding, and Validation capability boundaries are visible through public-safe action groups, inputs, validation visuals, and services.",
                "✓ Localization / RTL: culture, direction, mirrored layout, formatting, strings, and expansion facts are visible through MASLocalizationRtl.AttachPage without exposing localization internals.",
                "✓ Commercial Gate + SDK Harness: future changes must keep this chain valid.",
                "",
                "What this page must not overclaim:",
                "• The lightweight Quality Orchestrator is source/governance evidence only.",
                "• Runtime, package, and packed-consumer certification require the full quality runner proof matrix.",
                "• StaticOnly/local diagnostics are non-releaseable unless the report explicitly marks FullReleaseEligible=True."
            }

            Return String.Join(Environment.NewLine, lines)
        End Function

        Private Shared Function ResolveMainStatusText(status As NexamasUICertificationStatus) As String
            Select Case status
                Case NexamasUICertificationStatus.Certified
                    Return "Certified — ready to show"
                Case NexamasUICertificationStatus.CertifiedWithMonitoring
                    Return "Pass with warnings"
                Case NexamasUICertificationStatus.SourceCertifiedOnly
                    Return "Source-certified only"
                Case NexamasUICertificationStatus.EvidenceDeclared
                    Return "Declared evidence"
                Case NexamasUICertificationStatus.Blocked
                    Return "Blocked"
                Case Else
                    Return "Incomplete"
            End Select
        End Function

        Private Shared Function ResolveStatusText(status As NexamasUICertificationStatus) As String
            Select Case status
                Case NexamasUICertificationStatus.Certified
                    Return "Ready"
                Case NexamasUICertificationStatus.CertifiedWithMonitoring
                    Return "Ready + monitored"
                Case NexamasUICertificationStatus.SourceCertifiedOnly
                    Return "Source-only"
                Case NexamasUICertificationStatus.EvidenceDeclared
                    Return "Declared"
                Case NexamasUICertificationStatus.Blocked
                    Return "Blocked"
                Case Else
                    Return "Incomplete"
            End Select
        End Function

        Private Shared Function ResolveAreaText(entry As NexamasUICertificationEntry) As String
            If entry Is Nothing Then Return "Unknown"

            Select Case entry.SystemKey
                Case "quality-orchestrator"
                    Return "Quality Orchestrator"
                Case "quality-asset-presence"
                    Return "Quality assets"
                Case "architecture-validation"
                    Return "Architecture validation"
                Case "dead-path-closure"
                    Return "Dead paths"
                Case "component-coverage-map"
                    Return "Component coverage"
                Case "render-verification-coverage"
                    Return "Render coverage graph"
                Case "render-verification-readiness"
                    Return "Render readiness"
                Case "surface-material-proof"
                    Return "Surface material proof"
                Case "render-verification-element-coverage-closure"
                    Return "Render element coverage"
                Case "size-layout-runtime-verification"
                    Return "Size/Layout runtime"
                Case "size-layout-element-closure"
                    Return "Size/Layout elements"
                Case "localization-runtime-ownership"
                    Return "Localization runtime"
                Case "output-application-route"
                    Return "Output product"
                Case "performance-diagnostics-orchestration"
                    Return "Performance diagnostics"
                Case "performance"
                    Return "Performance"
                Case "render-verification"
                    Return "Visual proof"
                Case "virtualization"
                    Return "Large data"
                Case "datagrid"
                    Return "DataGrid"
                Case "floatruntime"
                    Return "Floating UI"
                Case "sdk-release-readiness"
                    Return "SDK API"
                Case "commercial-gate"
                    Return "Commercial gate"
                Case "sdk-harness"
                    Return "SDK tests"
                Case "showcase-pagehost-coverage"
                    Return "Showcase coverage gate"
                Case "showcase-business-controls"
                    Return "Chart + PropertyGrid"
                Case "showcase-search-datagrid"
                    Return "Search + DataGrid"
                Case "showcase-surface-materials"
                    Return "Surface Material Live Lab"
                Case "showcase-services"
                    Return "Services lab"
                Case "showcase-certification-refresh"
                    Return "Certification refresh"
                Case "showcase-diagnostics-dashboard"
                    Return "Diagnostics Dashboard"
                Case "showcase-layout-architecture"
                    Return "Application Architecture"
                Case "showcase-workflow-foundations"
                    Return "Workflow Foundations"
                Case "showcase-reportprint-foundation"
                    Return "Report / Print Foundation"
                Case "showcase-pluginmodule-foundation"
                    Return "Plugin / Module Foundation"
                Case "showcase-localization-rtl-host"
                    Return "Localization / RTL"
                Case Else
                    Return entry.DisplayName
            End Select
        End Function

        Private Shared Function ResolveProofText(entry As NexamasUICertificationEntry) As String
            If entry Is Nothing Then Return String.Empty

            Select Case entry.SystemKey
                Case "quality-orchestrator"
                    Return "Quality gates have one aggregator."
                Case "quality-asset-presence"
                    Return "Required assets are present or blocked."
                Case "architecture-validation"
                    Return "Architecture registry validation has no blockers."
                Case "dead-path-closure"
                    Return "Unowned source and parallel paths are blocked."
                Case "component-coverage-map"
                    Return "All descriptors have coverage classification."
                Case "render-verification-coverage"
                    Return "Targets, scenarios, and capture scenes are aligned."
                Case "render-verification-readiness"
                    Return "Target/scenario readiness is checked before capture."
                Case "surface-material-proof"
                    Return "Surface material proof maps to official visual scenarios."
                Case "render-verification-element-coverage-closure"
                    Return "Every descriptor has a dashboard evidence row."
                Case "size-layout-runtime-verification"
                    Return "Runtime size/layout facts are probed."
                Case "size-layout-element-closure"
                    Return "Registry, intrinsic, layout, and responsive facts match."
                Case "localization-runtime-ownership"
                    Return "Text lookup, RTL facts, and public host boundary are checked."
                Case "output-application-route"
                    Return "Public Output facade, capability catalog, chart/report manifests, product bundle, and unsupported PDF/print truth are checked."
                Case "performance-diagnostics-orchestration"
                    Return "Snapshots and dashboard truth are checked."
                Case "performance"
                    Return "Fast UI discipline is protected."
                Case "render-verification"
                    Return "Screens have visual proof."
                Case "virtualization"
                    Return "Huge data uses one shared engine."
                Case "datagrid"
                    Return "Commercial grid ownership is closed."
                Case "floatruntime"
                    Return "Dialogs and popups use one runtime."
                Case "sdk-release-readiness"
                    Return "SDK contract surface is frozen."
                Case "commercial-gate"
                    Return "Release gates protect the chain."
                Case "sdk-harness"
                    Return "Runtime harness baseline is stable."
                Case "showcase-pagehost-coverage"
                    Return "Visible pages are checked against public gateways."
                Case "showcase-business-controls"
                    Return "Charts and inspectors are visible."
                Case "showcase-search-datagrid"
                    Return "SearchBox strength is tied to data."
                Case "showcase-surface-materials"
                    Return "Surface material gateways are visible."
                Case "showcase-services"
                    Return "Official Nexamas UI services are demonstrated."
                Case "showcase-certification-refresh"
                    Return "The center mirrors current Showcase strength."
                Case "showcase-diagnostics-dashboard"
                    Return "Read-only diagnostics are visible."
                Case "showcase-layout-architecture"
                    Return "Application architecture is visible."
                Case "showcase-workflow-foundations"
                    Return "Workflow boundaries are visible."
                Case "showcase-reportprint-foundation"
                    Return "Report / Print boundary is visible."
                Case "showcase-pluginmodule-foundation"
                    Return "Plugin / Module boundary is visible."
                Case "showcase-localization-rtl-host"
                    Return "Localization / RTL host page is visible."
                Case Else
                    Return entry.Summary
            End Select
        End Function

        Private Shared Function ResolveOwnerText(entry As NexamasUICertificationEntry) As String
            If entry Is Nothing Then Return String.Empty

            Select Case entry.SystemKey
                Case "quality-orchestrator"
                    Return "CertificationSystem"
                Case "quality-asset-presence"
                    Return "CertificationSystem Gate"
                Case "architecture-validation"
                    Return "ArchitectureSystem Validator"
                Case "dead-path-closure"
                    Return "CertificationSystem Source Tree Gate"
                Case "component-coverage-map"
                    Return "CertificationSystem + ArchitectureSystem + RenderVerificationSystem"
                Case "render-verification-coverage"
                    Return "RenderVerificationSystem Coverage Audit"
                Case "render-verification-readiness"
                    Return "RenderVerificationSystem Readiness Gate"
                Case "surface-material-proof"
                    Return "RenderVerificationSystem Surface Material Proof Audit"
                Case "render-verification-element-coverage-closure"
                    Return "RenderVerificationSystem Element Coverage Closure Audit"
                Case "size-layout-runtime-verification"
                    Return "SizeLayoutSystem Runtime Verification Audit"
                Case "size-layout-element-closure"
                    Return "SizeLayoutSystem Element Closure Audit"
                Case "localization-runtime-ownership"
                    Return "LocalizationSystem Runtime Ownership Audit"
                Case "output-application-route"
                    Return "ApplicationSystem + OutputSystem Route Audit"
                Case "performance-diagnostics-orchestration"
                    Return "PerformanceSystem + DiagnosticsDashboardSystem Audit"
                Case "performance"
                    Return "PerformanceSystem"
                Case "render-verification"
                    Return "RenderVerificationSystem"
                Case "virtualization"
                    Return "VirtualizationSystem"
                Case "datagrid"
                    Return "MASDataGrid"
                Case "floatruntime"
                    Return "FloatRuntime"
                Case "sdk-release-readiness"
                    Return "CertificationSystem"
                Case "commercial-gate"
                    Return "eng/ci"
                Case "sdk-harness"
                    Return "eng/tests"
                Case "showcase-pagehost-coverage"
                    Return "NexamasUIShowcase eng/tests"
                Case "showcase-business-controls"
                    Return "NexamasUIShowcase PageHost"
                Case "showcase-search-datagrid"
                    Return "MASSearchTextBox + MASDataGrid public route"
                Case "showcase-surface-materials"
                    Return "VisualSurface public surface gateway route"
                Case "showcase-services"
                    Return "MASApplicationWindow.Services"
                Case "showcase-certification-refresh"
                    Return "CertificationSystem + Showcase coverage reports"
                Case "showcase-diagnostics-dashboard"
                    Return "DiagnosticsDashboardSystem host route"
                Case "showcase-layout-architecture"
                    Return "ApplicationSystem PageHost + MASApplicationLayoutPageBuilder"
                Case "showcase-workflow-foundations"
                    Return "NexamasUIShowcase public action/input/validation routes"
                Case "showcase-reportprint-foundation"
                    Return "ReportPrintSystem Friend foundation + Showcase capability decision"
                Case "showcase-pluginmodule-foundation"
                    Return "PluginModuleSystem Friend foundation + Showcase capability decision"
                Case "showcase-localization-rtl-host"
                    Return "LocalizationSystem host route"
                Case Else
                    Return entry.ClosureContractName
            End Select
        End Function

        Private Shared Function ResolvePlainMeaning(entry As NexamasUICertificationEntry) As String
            If entry Is Nothing Then Return "No details are available."

            Select Case entry.SystemKey
                Case "quality-orchestrator"
                    Return "Quality certification now flows through one internal orchestrator that aggregates lightweight gate results instead of relying only on static manifest declarations."
                Case "quality-asset-presence"
                    Return "The project tree must contain the scripts, docs, CI files, samples, packaging files, resources, and project-declared assets named by the official quality route."
                Case "architecture-validation"
                    Return "The registered architecture catalog must validate cleanly before certification trusts any higher-level ownership claims. This prevents Application, component, layout, and verification evidence from sitting on top of a broken registry."
                Case "dead-path-closure"
                    Return "The product source tree must not contain missing declared assets, duplicate project Includes, active MASSystem/Component/My Project VB files outside Nexamas.UI.vbproj, or root-level bin/obj outputs that behave like dead or parallel source paths."
                Case "component-coverage-map"
                    Return "Every registered MASComponentRegistry descriptor must be classified against direct render scenarios, family render scenarios, or explicit contract/system proof evidence, so no element remains invisible to Quality."
                Case "render-verification-coverage"
                    Return "Render Verification catalog targets, scenarios, capture-scene registrations, and component coverage entries must stay aligned so visual proof cannot drift from the actual component inventory."
                Case "render-verification-readiness"
                    Return "Render Verification targets and scenarios must have stable identity, deterministic file names, valid capture-scene ownership, safe dimensions, allowed DPI values, known themes, and an owned baseline store before any screenshot evidence is trusted."
                Case "surface-material-proof"
                    Return "Surface material proof must remain tied to the official runtime-surface visual consumer catalog, public gateway manifest, target catalog scenarios, and capture-scene registry instead of separate demo-only material screenshots."
                Case "render-verification-element-coverage-closure"
                    Return "The Render Verification dashboard must list every MASComponentRegistry descriptor using the existing component coverage map and target catalog. Direct and family rows resolve to catalog scenarios and capture scenes; contract/system rows remain explicit evidence rows instead of hidden elements."
                Case "size-layout-runtime-verification"
                    Return "Size/Layout verification now probes the live resolver/profile/DPI/size-contract path for normal, compact, tiny, and collapsed bounds, and it composes the existing responsive, bypass, weak-path, source-contract, migration, surface-boundary, and behavioral lockdown audits."
                Case "size-layout-element-closure"
                    Return "Every registered MASComponentRegistry descriptor must have responsive-consumption evidence, and every concrete registered MASControlBase element must expose intrinsic-size and Friend-only layout-participant contracts. This keeps element ownership in the existing registry and Size/Layout systems instead of a parallel element list."
                Case "localization-runtime-ownership"
                    Return "Localization now has one Friend-owned runtime resolver for product strings, one culture/direction source for RTL and mirrored layout facts, and one public host route through MASLocalizationRtl.AttachPage. Catalogs and translation lookup stay internal instead of becoming public or Showcase-owned."
                Case "output-application-route"
                    Return "Output now has a public MASApplication.Output product facade with governed request/result/capability catalog contracts, directory/file destinations, PNG visual capture, overwrite protection, and a product evidence bundle. Chart/Visualization, Report/Print, and Render Verification internals remain Friend-owned behind the Application route."
                Case "performance-diagnostics-orchestration"
                    Return "Performance and Diagnostics are now checked as one read-only evidence chain: budgets must be sane, snapshots must preserve layout/render refresh counters, the dashboard must not pretend missing owner facts are available, virtualization facts must bridge from PerformanceSystem, and release certification must remain complete."
                Case "performance"
                    Return "The platform has an evidence chain for performance pressure, budgets, remediation, and release readiness."
                Case "render-verification"
                    Return "The important screens and product states are covered by official render-verification evidence instead of manual screenshots."
                Case "virtualization"
                    Return "Large data surfaces are protected by the shared virtualization system, not by private control-specific engines."
                Case "datagrid"
                    Return "The commercial DataGrid runtime is closed across layout, columns, rows, selection, editing, summaries, pinned/wide columns, and virtualization consumption."
                Case "floatruntime"
                    Return "Floating UI surfaces are governed by one FloatRuntime route, so dialogs, popups, and overlays do not drift into separate ownership paths."
                Case "sdk-release-readiness"
                    Return "The public SDK contract is frozen and documented, while internal governance remains Friend-only."
                Case "commercial-gate"
                    Return "The main commercial gate has registrations that protect the certification chain from accidental regression."
                Case "sdk-harness"
                    Return "The runtime harness baseline remains stable, so certification is tied to executable SDK behavior."
                Case "showcase-pagehost-coverage"
                    Return "The external Showcase is no longer allowed to silently miss public Nexamas UI control gateways or capability decisions."
                Case "showcase-business-controls"
                    Return "Chart Dashboard and PropertyGrid Inspector prove that business dashboards and inspector/editor scenarios are visible in the active Showcase."
                Case "showcase-search-datagrid"
                    Return "Advanced SearchBox behavior is demonstrated where it matters commercially: suggestions, recents, tokens, commit, and DataGrid binding in one scenario."
                Case "showcase-surface-materials"
                    Return "The Surface Materials page shows live broad-surface material switching through public gateways while keeping interactive controls and internals outside the material route."
                Case "showcase-services"
                    Return "The Services page demonstrates the public application-service facade instead of using native dialogs or service internals."
                Case "showcase-certification-refresh"
                    Return "The Certification Center now tells the user which visible Showcase areas correspond to the current Nexamas UI product strengths."
                Case "showcase-diagnostics-dashboard"
                    Return "The Diagnostics Dashboard page is hosted through MASDiagnosticsDashboard.AttachDashboard, so users can see performance, layout, virtualization, and baseline-awareness rows without Showcase owning telemetry."
                Case "showcase-layout-architecture"
                    Return "The Application Architecture page proves that Nexamas UI owns PageHost navigation, Shell-aware page presets, semantic layout builders, and host-level surface boundaries while Showcase only declares public page intent."
                Case "showcase-workflow-foundations"
                    Return "The Workflow Foundations page explains Command / Action, Data Binding, and Form Validation capability boundaries while demonstrating only public-safe action groups, fields, validation visuals, and services."
                Case "showcase-reportprint-foundation"
                    Return "The Commercial Foundations page explains Report / Print as a certified Friend-owned foundation and deliberately avoids public print commands, PDF export, report designers, native print dialogs, and Showcase-owned report models."
                Case "showcase-pluginmodule-foundation"
                    Return "The Commercial Foundations page explains Plugin / Module as a certified Friend-owned foundation and deliberately avoids external plugin loading, module execution, demo-owned registries, wrappers, adapters, bridges, and parallel extension hosts."
                Case "showcase-localization-rtl-host"
                    Return "The Localization / RTL page is hosted through MASLocalizationRtl.AttachPage, so users can see cultures, direction, mirrored layout, formatting, localized strings, and expansion behavior without Showcase reading localization internals or mutating thread culture."
                Case Else
                    Return entry.Summary
            End Select
        End Function
    End Class

End Namespace
