﻿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 CreateSampleTileBitmap(color As SKColor) As SKBitmap
        ' Demo payload only: MASTileBox consumes SKBitmap thumbnails through its public API.
        ' Showcase does not draw tile chrome, layout, hover, selection, radius, or surface material.
        Dim bitmap As New SKBitmap(160, 108)
        bitmap.Erase(color)
        Return bitmap
    End Function

    Private Shared Sub BuildGridData(grid As MASDataGrid)
        grid.SelectionMode = MASDataGridSelectionMode.Cell
        grid.RowHeightDip = 32.0F
        grid.HeaderHeightDip = 42.0F

        Dim idColumn As MASDataGridColumn = grid.AddColumn("id", "ID").WithWidth(72.0F).ReadOnlyColumn()
        idColumn.ValueTypeCode = TypeCode.Int32
        idColumn.TextAlignment = MASHorizontalAlignment.Right
        idColumn.CanResize = False
        Dim nameColumn As MASDataGridColumn = grid.AddColumn("name", "Capability").WithWidth(210.0F)
        nameColumn.ValueTypeCode = TypeCode.String
        Dim systemColumn As MASDataGridColumn = grid.AddColumn("system", "System").WithWidth(185.0F)
        systemColumn.ValueTypeCode = TypeCode.String
        Dim statusColumn As MASDataGridColumn = grid.AddColumn("status", "Status").WithWidth(120.0F)
        statusColumn.ValueTypeCode = TypeCode.String
        Dim scoreColumn As MASDataGridColumn = grid.AddColumn("score", "Score").WithWidth(104.0F)
        scoreColumn.ValueTypeCode = TypeCode.Decimal
        scoreColumn.FormatString = "0.0"
        scoreColumn.TextAlignment = MASHorizontalAlignment.Right
        Dim deltaColumn As MASDataGridColumn = grid.AddColumn("delta", "Δ Quality").WithWidth(112.0F)
        deltaColumn.ValueTypeCode = TypeCode.Decimal
        deltaColumn.FormatString = "+0.0;-0.0;0.0"
        deltaColumn.TextAlignment = MASHorizontalAlignment.Right
        Dim activeColumn As MASDataGridColumn = grid.AddColumn("active", "Active").WithWidth(104.0F)
        activeColumn.ValueTypeCode = TypeCode.Boolean
        activeColumn.TextAlignment = MASHorizontalAlignment.Center
        Dim dueColumn As MASDataGridColumn = grid.AddColumn("due", "Due").WithWidth(130.0F)
        dueColumn.ValueTypeCode = TypeCode.DateTime
        dueColumn.FormatString = "dd.MM.yyyy"
        Dim ownerColumn As MASDataGridColumn = grid.AddColumn("owner", "Owner").WithWidth(150.0F)
        ownerColumn.ValueTypeCode = TypeCode.String
        Dim regionColumn As MASDataGridColumn = grid.AddColumn("region", "Region").WithWidth(132.0F)
        regionColumn.ValueTypeCode = TypeCode.String
        Dim notesColumn As MASDataGridColumn = grid.AddColumn("notes", "Notes").WithWidth(280.0F)
        notesColumn.ValueTypeCode = TypeCode.String
        notesColumn.CanSort = False

        Dim systems As String() = New String() {"Render Verification", "Virtualization", "DataGrid", "Motion", "Theme / Readability", "Localization", "Presentation", "Application"}
        Dim owners As String() = New String() {"SDK Core", "Controls", "Runtime", "Product", "Theme", "QA"}
        Dim regions As String() = New String() {"EU", "DE", "MENA", "Global"}

        Using grid.DataView.DeferRefresh()
            For index As Integer = 1 To 1200
                Dim systemName As String = systems((index - 1) Mod systems.Length)
                Dim owner As String = owners((index - 1) Mod owners.Length)
                Dim region As String = regions((index - 1) Mod regions.Length)
                Dim status As String = ResolveStatus(index)
                Dim score As Decimal = 68D + CDec((index * 17) Mod 31) + (CDec(index Mod 10) / 10D)
                Dim delta As Decimal = (CDec(index Mod 15) - 7D) / 10D
                Dim active As Boolean = index Mod 6 <> 0
                Dim due As DateTime = DateTime.Today.AddDays((index Mod 90) - 22)
                grid.AddRow(index, "SDK capability " & index.ToString("0000", CultureInfo.InvariantCulture), systemName, status, score, delta, active, due, owner, region, ResolveNote(index))
            Next
        End Using
        grid.SelectedRowIndex = 0
        grid.SelectedColumnIndex = ScoreColumnIndex
    End Sub

    Private Shared Function ResolveStatus(index As Integer) As String
        If index Mod 23 = 0 Then Return "Blocked"
        If index Mod 9 = 0 Then Return "Review"
        Return "Ready"
    End Function

    Private Shared Function ResolveNote(index As Integer) As Object
        If index Mod 17 = 0 Then Return Nothing
        If index Mod 23 = 0 Then Return "Blocked until gate proof is refreshed"
        If index Mod 9 = 0 Then Return "Needs architecture review before promotion"
        If index Mod 11 = 0 Then Return "Edited cells show modified markers after commit"
        Return "Right-click header for column menu; Shift+wheel moves wide columns"
    End Function

    Private Shared Sub EnsureVisibleScoreSelection(grid As MASDataGrid)
        If grid Is Nothing OrElse grid.VisibleRowCount <= 0 Then Return
        If grid.SelectedRowIndex < 0 OrElse grid.SelectedRowIndex >= grid.VisibleRowCount Then grid.SelectedRowIndex = 0
        grid.SelectedColumnIndex = ScoreColumnIndex
    End Sub

    Private Shared Function BuildClipboardPreview(text As String) As String
        If String.IsNullOrWhiteSpace(text) Then Return "No selected cell text yet. Select a cell/range or use Ctrl+Shift+C for headers."
        Dim normalized As String = text.Replace(ControlChars.Cr, " "c).Replace(ControlChars.Lf, " "c)
        If normalized.Length > 140 Then normalized = normalized.Substring(0, 140) & "…"
        Return "Copied TSV preview: " & normalized
    End Function


    Private Shared Sub AddReadOnlyDataGridColumn(grid As MASDataGrid,
                                                 key As String,
                                                 header As String,
                                                 widthDip As Single,
                                                 Optional canSort As Boolean = False)
        If grid Is Nothing Then Return
        Dim column As MASDataGridColumn = grid.AddColumn(key, header).WithWidth(widthDip).ReadOnlyColumn()
        column.CanSort = canSort
    End Sub

    Private Shared Sub PopulateOutputCapabilityRows(view As MASListView,
                                                    catalog As MASOutputCapabilityCatalog)
        If view Is Nothing Then Return
        view.ClearItems()

        If catalog Is Nothing OrElse catalog.Capabilities Is Nothing OrElse catalog.Capabilities.Count = 0 Then
            view.Add(MASListViewItem.Create("Capability catalog").WithSubItems(New String() {"Unavailable", "-", "Missing", "No public capability rows were returned.", ""}))
            Return
        End If

        For Each capability As MASOutputCapability In catalog.Capabilities
            If capability Is Nothing Then Continue For
            view.Add(MASListViewItem.Create(capability.Name).WithSubItems(New String() {
                capability.ArtifactKind.ToString(),
                capability.Format.ToString(),
                capability.Status.ToString(),
                capability.TargetSummary,
                capability.DefaultFileName
            }))
        Next
    End Sub

    Private Shared Sub PopulateOutputCapabilityRows(grid As MASDataGrid,
                                                    catalog As MASOutputCapabilityCatalog)
        If grid Is Nothing Then Return
        grid.DataView.ClearRows()

        If catalog Is Nothing OrElse catalog.Capabilities Is Nothing OrElse catalog.Capabilities.Count = 0 Then
            grid.AddRow("Capability catalog", "Unavailable", "-", "Missing", "No public capability rows were returned.", "")
            grid.SelectedRowIndex = 0
            Return
        End If

        For Each capability As MASOutputCapability In catalog.Capabilities
            If capability Is Nothing Then Continue For
            grid.AddRow(capability.Name,
                        capability.ArtifactKind.ToString(),
                        capability.Format.ToString(),
                        capability.Status.ToString(),
                        capability.TargetSummary,
                        capability.DefaultFileName)
        Next

        grid.SelectedRowIndex = 0
    End Sub

    Private Shared Sub PopulateOutputResultRows(view As MASListView,
                                                application As MASApplication)
        If view Is Nothing Then Return
        view.ClearItems()

        If application Is Nothing OrElse application.IsDisposed Then
            view.Add(MASListViewItem.Create("Application.Output").WithSubItems(New String() {"Unavailable", "No facade", "Shared MASApplication was not available."}))
            Return
        End If

        AddOutputResultRow(view, "Catalog memory", application.Output.ExportCapabilityCatalogManifest(MASOutputFormat.Json))
        AddOutputResultRow(view, "Readiness text", application.Output.ExportReadinessManifest(MASOutputFormat.PlainText))
        AddOutputResultRow(view, "Visual PNG memory", application.Output.ExportVisualCapturePng(MASOutputTarget.Memory(), MASOutputOptions.ForVisualCapture("showcase-real-buttons-light-1x")))
        AddOutputResultRow(view, "PDF unsupported", application.Output.Export(New MASOutputRequest(MASOutputArtifactKind.PdfDocument, MASOutputFormat.Pdf, MASOutputTarget.Memory())))
    End Sub

    Private Shared Sub AddOutputResultRow(view As MASListView,
                                          proofName As String,
                                          result As MASOutputResult)
        If view Is Nothing Then Return
        If result Is Nothing Then
            view.Add(MASListViewItem.Create(If(proofName, String.Empty)).WithSubItems(New String() {"No result", "0", "The Output facade returned Nothing."}))
            Return
        End If

        Dim payload As String = If(result.ContentByteCount > 0,
                                   result.ContentByteCount.ToString(CultureInfo.InvariantCulture) & " bytes",
                                   If(result.Content.Length > 0,
                                      result.Content.Length.ToString(CultureInfo.InvariantCulture) & " chars",
                                      If(result.ArtifactPath.Length > 0, "file", "none")))
        Dim route As String = If(result.ArtifactPath.Length > 0, result.ArtifactPath, result.FailureReason.ToString())
        view.Add(MASListViewItem.Create(If(proofName, String.Empty)).WithSubItems(New String() {
            result.Status.ToString(),
            payload,
            route
        }))
    End Sub

    Private Shared Sub PopulateOutputResultRows(grid As MASDataGrid,
                                                application As MASApplication)
        If grid Is Nothing Then Return
        grid.DataView.ClearRows()

        If application Is Nothing OrElse application.IsDisposed Then
            grid.AddRow("Application.Output", "Unavailable", "No facade", "Shared MASApplication was not available.")
            grid.SelectedRowIndex = 0
            Return
        End If

        AddOutputResultRow(grid, "Catalog memory", application.Output.ExportCapabilityCatalogManifest(MASOutputFormat.Json))
        AddOutputResultRow(grid, "Readiness text", application.Output.ExportReadinessManifest(MASOutputFormat.PlainText))
        AddOutputResultRow(grid, "Visual PNG memory", application.Output.ExportVisualCapturePng(MASOutputTarget.Memory(), MASOutputOptions.ForVisualCapture("showcase-real-buttons-light-1x")))
        AddOutputResultRow(grid, "PDF unsupported", application.Output.Export(New MASOutputRequest(MASOutputArtifactKind.PdfDocument, MASOutputFormat.Pdf, MASOutputTarget.Memory())))
        grid.SelectedRowIndex = 0
    End Sub

    Private Shared Sub AddOutputResultRow(grid As MASDataGrid,
                                          proofName As String,
                                          result As MASOutputResult)
        If grid Is Nothing Then Return
        If result Is Nothing Then
            grid.AddRow(If(proofName, String.Empty), "No result", "0", "The Output facade returned Nothing.")
            grid.SelectedRowIndex = Math.Max(0, grid.Rows.Count - 1)
            Return
        End If

        Dim payload As String = If(result.ContentByteCount > 0,
                                   result.ContentByteCount.ToString(CultureInfo.InvariantCulture) & " bytes",
                                   If(result.Content.Length > 0,
                                      result.Content.Length.ToString(CultureInfo.InvariantCulture) & " chars",
                                      If(result.ArtifactPath.Length > 0, "file", "none")))
        Dim route As String = If(result.ArtifactPath.Length > 0, result.ArtifactPath, result.FailureReason.ToString())
        grid.AddRow(If(proofName, String.Empty),
                    result.Status.ToString(),
                    payload,
                    route)
        grid.SelectedRowIndex = Math.Max(0, grid.Rows.Count - 1)
    End Sub

    Private Shared Function BuildOutputResultText(operationName As String,
                                                  result As MASOutputResult) As String
        If result Is Nothing Then Return If(operationName, "Output operation") & ": no result returned."
        Dim payload As String = If(result.ContentByteCount > 0,
                                   result.ContentByteCount.ToString(CultureInfo.InvariantCulture) & " bytes",
                                   If(result.Content.Length > 0,
                                      result.Content.Length.ToString(CultureInfo.InvariantCulture) & " chars",
                                      If(result.ArtifactPath.Length > 0, result.ArtifactPath, "no payload")))
        Return If(operationName, "Output operation") & ": " & result.Status.ToString() & " | " & payload & " | " & result.Summary
    End Function

    Private Shared Sub PopulateElementCoverageRows(view As MASListView)
        If view Is Nothing Then Return
        view.ClearItems()
        AddElementCoverageRow(view, "AddTitle / MASTitle", "element.coverage", "Live proof through Window.Controls.AddTitle(...); no longer hidden as metadata-only infrastructure.")
        AddElementCoverageRow(view, "Button family", "buttons", "AddButton, AddSplitButton, choice controls, dialog actions, and state coverage are grouped on the Buttons page.")
        AddElementCoverageRow(view, "Input family", "inputs", "Text, search, password, numeric, multiline, path, combo, date, date-range, CalendarView, time, validation message, tag input, slider, and data-form are shown together.")
        AddElementCoverageRow(view, "Selection transfer family", "selection", "SegmentedControl, SelectorItem, TransferList, and Tabs are shown together as selection/navigation controls without storage or binding ownership.")
        AddElementCoverageRow(view, "Feedback/status family", "feedback.status", "Badge, Rating, StatusBanner, EmptyState, NotificationPanel, Avatar, AvatarGroup, Timeline, and identity/status surfaces are visible in one product page.")
        AddElementCoverageRow(view, "Productivity/navigation family", "productivity.navigation / planning.workspace", "MenuBar, CommandBar, CommandPalette, Breadcrumb, Expander, Accordion, FilterBar, Pagination, LoadingSkeleton, ContentCarousel, KanbanBoard, and AgendaView are shown as business-workspace controls.")
        AddElementCoverageRow(view, "Workflow family", "workflow.foundations", "Stepper and Wizard are visible as guided-flow controls while workflow, binding, and validation foundations stay Nexamas.UI-owned.")
        AddElementCoverageRow(view, "Services and floating surfaces", "services", "Dialogs, toasts, tooltips, context menus, Callout, Popover, Drawer, SidePanel, file services, and progress are exercised through official service/control gateways.")
        AddElementCoverageRow(view, "Data and analytics surfaces", "datagrid / data.analytics / lists.tree / tiles / virtualization", "DataGrid, DataView, MetricCard, FilterBuilder, TreeGrid, PivotTable, ListBox, ListView, TreeView, TileBox, and large-item virtualization proofs are separated into focused pages.")
        AddElementCoverageRow(view, "Visual editor surfaces", "visual.editors", "ColorPicker, color-choice editing, and MAS-owned EmptyState material surfaces are shown without opening a native color dialog or theme-designer engine.")
        AddElementCoverageRow(view, "File surfaces", "file.surfaces", "FileDropZone, FilePickerControl, and FileExplorerView are shown as embedded MAS controls; hosted file services remain on the Services page.")
        AddElementCoverageRow(view, "Charts and inspectors", "charts.dashboard / property.inspector", "Chart and PropertyGrid have dedicated product pages instead of being buried in diagnostic text.")
        AddElementCoverageRow(view, "Surface/material family", "surface.materials", "Surface material selection, GroupBox, Progress, OperationProgressBox, Toolbar, TopBar route, and MASCard material proof stay on the live material lab page.")
        AddElementCoverageRow(view, "Shell menu trigger / MASMenuButton", "shell-owned route", "Created and bound through window.Shell menu trigger routes; not inserted into PageHost MAS child slots or rebuilt as a native sample.")
        AddElementCoverageRow(view, "DropDown and context menus", "buttons / productivity.navigation / services", "MASDropDownMenuBuilder is exercised by SplitButton, MenuBar, CommandBar split commands, and context-menu service routes.")
        AddElementCoverageRow(view, "Certification and system hosts", "certification.center / diagnostics.dashboard / render.verification", "Nexamas.UI-owned host pages attach their official surfaces; Showcase hosts them but does not own evidence, diagnostics, or capture logic.")
        AddElementCoverageRow(view, "Application layout and sizing", "application.architecture / settings.sizing", "PageHost, semantic layout builders, action groups, split panes, and runtime size profile switching are visible as platform architecture.")
    End Sub

    Private Shared Sub AddElementCoverageRow(view As MASListView,
                                             elementName As String,
                                             activeRoute As String,
                                             coverageDecision As String)
        If view Is Nothing Then Return
        view.Add(MASListViewItem.Create(If(elementName, String.Empty)).WithSubItems(New String() {If(activeRoute, String.Empty), If(coverageDecision, String.Empty)}))
    End Sub

    Private Shared Sub PopulateElementCoverageRows(grid As MASDataGrid)
        If grid Is Nothing Then Return
        grid.DataView.ClearRows()
        AddElementCoverageRow(grid, "AddTitle / MASTitle", "element.coverage", "Live proof through Window.Controls.AddTitle(...); no longer hidden as metadata-only infrastructure.")
        AddElementCoverageRow(grid, "Button family", "buttons", "AddButton, AddSplitButton, choice controls, dialog actions, and state coverage are grouped on the Buttons page.")
        AddElementCoverageRow(grid, "Input family", "inputs", "Text, search, password, numeric, multiline, path, combo, date, date-range, CalendarView, time, validation message, tag input, slider, and data-form are shown together.")
        AddElementCoverageRow(grid, "Selection transfer family", "selection", "SegmentedControl, SelectorItem, TransferList, and Tabs are shown together as selection/navigation controls without storage or binding ownership.")
        AddElementCoverageRow(grid, "Feedback/status family", "feedback.status", "Badge, Rating, StatusBanner, EmptyState, NotificationPanel, Avatar, AvatarGroup, Timeline, and identity/status surfaces are visible in one product page.")
        AddElementCoverageRow(grid, "Productivity/navigation family", "productivity.navigation / planning.workspace", "MenuBar, CommandBar, CommandPalette, Breadcrumb, Expander, Accordion, FilterBar, Pagination, LoadingSkeleton, ContentCarousel, KanbanBoard, and AgendaView are shown as business-workspace controls.")
        AddElementCoverageRow(grid, "Workflow family", "workflow.foundations", "Stepper and Wizard are visible as guided-flow controls while workflow, binding, and validation foundations stay Nexamas.UI-owned.")
        AddElementCoverageRow(grid, "Services and floating surfaces", "services", "Dialogs, toasts, tooltips, context menus, Callout, Popover, Drawer, SidePanel, file services, and progress are exercised through official service/control gateways.")
        AddElementCoverageRow(grid, "Data and analytics surfaces", "datagrid / data.analytics / lists.tree / tiles / virtualization", "DataGrid, DataView, MetricCard, FilterBuilder, TreeGrid, PivotTable, ListBox, ListView, TreeView, TileBox, and large-item virtualization proofs are separated into focused pages.")
        AddElementCoverageRow(grid, "Visual editor surfaces", "visual.editors", "ColorPicker, color-choice editing, and MAS-owned EmptyState material surfaces are shown without opening a native color dialog or theme-designer engine.")
        AddElementCoverageRow(grid, "File surfaces", "file.surfaces", "FileDropZone, FilePickerControl, and FileExplorerView are shown as embedded MAS controls; hosted file services remain on the Services page.")
        AddElementCoverageRow(grid, "Charts and inspectors", "charts.dashboard / property.inspector", "Chart and PropertyGrid have dedicated product pages instead of being buried in diagnostic text.")
        AddElementCoverageRow(grid, "Surface/material family", "surface.materials", "Surface material selection, GroupBox, Progress, OperationProgressBox, Toolbar, TopBar route, and MASCard material proof stay on the live material lab page.")
        AddElementCoverageRow(grid, "Shell menu trigger / MASMenuButton", "shell-owned route", "Created and bound through window.Shell menu trigger routes; not inserted into PageHost MAS child slots or rebuilt as a native sample.")
        AddElementCoverageRow(grid, "DropDown and context menus", "buttons / productivity.navigation / services", "MASDropDownMenuBuilder is exercised by SplitButton, MenuBar, CommandBar split commands, and context-menu service routes.")
        AddElementCoverageRow(grid, "Certification and system hosts", "certification.center / diagnostics.dashboard / render.verification", "Nexamas.UI-owned host pages attach their official surfaces; Showcase hosts them but does not own evidence, diagnostics, or capture logic.")
        AddElementCoverageRow(grid, "Application layout and sizing", "application.architecture / settings.sizing", "PageHost, semantic layout builders, action groups, split panes, and runtime size profile switching are visible as platform architecture.")
        grid.SelectedRowIndex = 0
    End Sub

    Private Shared Sub AddElementCoverageRow(grid As MASDataGrid,
                                             elementName As String,
                                             activeRoute As String,
                                             coverageDecision As String)
        If grid Is Nothing Then Return
        grid.AddRow(If(elementName, String.Empty), If(activeRoute, String.Empty), If(coverageDecision, String.Empty))
    End Sub

    Private Shared Sub PopulateProductivityNavigationRows(view As MASListView)
        If view Is Nothing Then Return
        view.ClearItems()
        view.Add(MASListViewItem.Create("AddMenuBar").WithSubItems(New String() {"Window.Controls.AddMenuBar(...) / MASDropDownMenuBuilder", "Shell-owned MainMenuBar attached once below the TopBar; not admitted into PageHost content, no MenuStrip, ToolStrip, or second flyout service."}))
        view.Add(MASListViewItem.Create("AddCommandBar").WithSubItems(New String() {"Window.Controls.AddCommandBar(...) / MASToolbar.AddCommand(...) / MASToolbar.AddSplitCommand(...)", "Upgraded MASToolbar command surface; no public MASCommandBar wrapper or command service."}))
        view.Add(MASListViewItem.Create("AddCommandPalette").WithSubItems(New String() {"Window.Controls.AddCommandPalette(...) / MASCommandPalette.AddCommand(...)", "Public command search surface; Showcase does not import the command registry, scanners, hooks, or command services."}))
        view.Add(MASListViewItem.Create("AddBreadcrumb").WithSubItems(New String() {"Window.Controls.AddBreadcrumb(...)", "Same-surface trail only; host owns page navigation/history."}))
        view.Add(MASListViewItem.Create("AddExpander").WithSubItems(New String() {"Window.Controls.AddExpander(...)", "Disclosure content through MASLayout/PageHost only; no custom panel or visibility engine."}))
        view.Add(MASListViewItem.Create("AddAccordion").WithSubItems(New String() {"Window.Controls.AddAccordion(...)", "Grouped disclosure sections through the official control; no duplicated expander logic in Showcase."}))
        view.Add(MASListViewItem.Create("FilterBar").WithSubItems(New String() {"page.FilterBar(...).SearchBox/ComboBox/DatePicker/ClearAction/ApplyAction", "Semantic layout builder only; no query service or DataGrid adapter."}))
        view.Add(MASListViewItem.Create("AddPagination").WithSubItems(New String() {"Window.Controls.AddPagination(...)", "Page selection only; host owns data loading/projection."}))
        view.Add(MASListViewItem.Create("AddLoadingSkeleton").WithSubItems(New String() {"Window.Controls.AddLoadingSkeleton(...)", "Visual placeholder only; no timer, thread, task, or progress lifetime."}))
    End Sub

    Private Shared Sub PopulateCommercialFoundationRows(view As MASListView)
        If view Is Nothing Then Return
        view.ClearItems()
        view.Add(MASListViewItem.Create("Report / Print").WithSubItems(New String() {"Shown as certified foundation decision", "No public print command, PDF export, report designer, or Showcase-owned reporting model."}))
        view.Add(MASListViewItem.Create("Plugin / Module").WithSubItems(New String() {"Shown as certified foundation decision", "No dynamic plugin loader, external module execution, or demo-owned extension host."}))
        view.Add(MASListViewItem.Create("Certification").WithSubItems(New String() {"Certification Center row + coverage report", "Showcase does not run gates, scan reports, or read internal foundation manifests."}))
        view.Add(MASListViewItem.Create("PageHost route").WithSubItems(New String() {"commercial.foundations", "A product-facing decision page only; not a new public foundation API."}))
    End Sub

    Private Shared Sub PopulateCommercialFoundationHostRows(view As MASListView)
        If view Is Nothing Then Return
        view.ClearItems()
        view.Add(MASListViewItem.Create("Report preview host").WithSubItems(New String() {"Future Nexamas.UI-owned preview/export host may consume official report preview facts.", "Do not build a Showcase report model, PDF exporter, native print route, or third-party reporting wrapper."}))
        view.Add(MASListViewItem.Create("Module catalog host").WithSubItems(New String() {"Future Nexamas.UI-owned catalog may display registered module descriptors and contributions.", "Do not load external assemblies, execute plugins, or create a demo-owned module registry."}))
        view.Add(MASListViewItem.Create("Certification-only status").WithSubItems(New String() {"Until public hosts exist, value is shown through certification, architecture, and boundary decisions.", "Do not mark the systems as live product pages that execute unavailable hosts."}))
    End Sub

    Private Shared Sub PopulateWorkflowFoundationRows(view As MASListView)
        If view Is Nothing Then Return
        view.ClearItems()
        view.Add(MASListViewItem.Create("Command / Action").WithSubItems(New String() {"page.ActionGroup + MASButton.Click + Window.Services feedback", "Command / Action foundation keeps registry/binding lifecycle internal until a public host is deliberately opened."}))
        view.Add(MASListViewItem.Create("Binding story").WithSubItems(New String() {"Input Text / ComboBox selection / Toggle state shown as one preview", "Data Binding foundation remains Nexamas.UI-owned; Showcase does not import binder contracts or reflection snapshots."}))
        view.Add(MASListViewItem.Create("Validation visuals").WithSubItems(New String() {"MASTextBox.SetValidation / ClearValidation / ValidationState", "Form Validation foundation remains Nexamas.UI-owned; public text inputs expose only safe visual feedback."}))
        view.Add(MASListViewItem.Create("Form validation summary").WithSubItems(New String() {"Window.Controls.AddFormValidationSummary(...)", "Form-level message aggregation is visual only; Showcase does not run rule engines, bind form sessions, or import foundation snapshots."}))
        view.Add(MASListViewItem.Create("Stepper / Wizard").WithSubItems(New String() {"Window.Controls.AddStepper(...) + AddWizard(...)", "Guided-flow visuals remain a public control recipe; Showcase does not create a workflow engine or page-state registry."}))
        view.Add(MASListViewItem.Create("Submit feedback").WithSubItems(New String() {"Window.Services.Toasts + Window.Services.Dialogs", "Submit policy and form-session governance stay inside Nexamas.UI foundations, not the external demo."}))
        view.Add(MASListViewItem.Create("Capability decision").WithSubItems(New String() {"workflow.foundations PageHost route", "This page is product-facing coverage, not a new public workflow engine."}))
    End Sub

    Private Shared Sub RefreshWorkflowEvidenceRows(view As MASListView,
                                                   nameText As String,
                                                   emailText As String,
                                                   roleText As String,
                                                   validationState As String)
        If view Is Nothing Then Return
        view.ClearItems()
        view.Add(MASListViewItem.Create("Name").WithSubItems(New String() {If(nameText, String.Empty), ResolveWorkflowFieldState(nameText, minLength:=3, requireEmailLike:=False, currentState:=validationState)}))
        view.Add(MASListViewItem.Create("Contact").WithSubItems(New String() {If(emailText, String.Empty), ResolveWorkflowFieldState(emailText, minLength:=3, requireEmailLike:=True, currentState:=validationState)}))
        view.Add(MASListViewItem.Create("Role").WithSubItems(New String() {If(roleText, String.Empty), If(String.IsNullOrWhiteSpace(roleText), "Missing", "Ready")}))
        view.Add(MASListViewItem.Create("Submit action").WithSubItems(New String() {"Validate -> Submit workflow", If(validationState, "Preview")}))
    End Sub

    Private Shared Function ResolveWorkflowFieldState(value As String,
                                                      minLength As Integer,
                                                      requireEmailLike As Boolean,
                                                      currentState As String) As String
        Dim text As String = If(value, String.Empty).Trim()
        If String.Equals(currentState, "Preview", StringComparison.OrdinalIgnoreCase) Then Return "Preview only"
        If text.Length < minLength Then Return "Error"
        If requireEmailLike AndAlso (Not text.Contains("@") OrElse Not text.Contains(".")) Then Return "Error"
        Return "Success"
    End Function

    Private Shared Sub PopulateApplicationArchitectureRows(view As MASListView)
        If view Is Nothing Then Return
        view.ClearItems()
        view.Add(MASListViewItem.Create("Window.Pages").WithSubItems(New String() {"RegisterPage / NavigateTo / Show", "ApplicationSystem owns same-window navigation and workspace replacement."}))
        view.Add(MASListViewItem.Create("ApplicationPage").WithSubItems(New String() {"page.ApplicationPage(MASApplicationPageLayoutKind.Dashboard, window.Shell)", "Nexamas.UI resolves top-bar reservation, padding, spacing, and content width."}))
        view.Add(MASListViewItem.Create("SplitPane").WithSubItems(New String() {"page.SplitPane(...)", "Narrative plus surface layout is resolved by MASLayout, not local panel math."}))
        view.Add(MASListViewItem.Create("AppLayout").WithSubItems(New String() {"Window.Controls.AddAppLayout(...)", "Responsive app-layout regions are visual MAS surfaces, not a router, PageHost owner, or shell engine."}))
        view.Add(MASListViewItem.Create("SplitView").WithSubItems(New String() {"Window.Controls.AddSplitView(...)", "Resizable left/content/right workspace panes remain visual split surfaces, not a dock engine or child host."}))
        view.Add(MASListViewItem.Create("FilterBar").WithSubItems(New String() {"page.FilterBar(...).Field(...)", "Filter rows wrap and size through semantic layout builders."}))
        view.Add(MASListViewItem.Create("FormRow").WithSubItems(New String() {"page.FormRow(...).Label(...).Input(...)", "Label/input/settings rows stay aligned without hand-coded positions."}))
        view.Add(MASListViewItem.Create("Gallery").WithSubItems(New String() {"page.Gallery(...).PreviewTiles().Columns(3)", "Responsive tile/card surfaces use semantic sizes and wrapping."}))
        view.Add(MASListViewItem.Create("ActionGroup").WithSubItems(New String() {"page.ActionGroup(...).AlignCenter()", "Action rows use MASLayout alignment with natural button sizing instead of full-width button strips."}))
        view.Add(MASListViewItem.Create("Surface host").WithSubItems(New String() {"LayoutApplicationSurface / ApplicationSurfaceLayoutBuilder", "Host-level chrome and region layout remain Nexamas.UI-owned; child pages do not redraw the parent surface."}))
    End Sub

    Private Shared Sub PopulateServicesGatewayRows(view As MASListView)
        If view Is Nothing Then Return
        view.ClearItems()
        view.Add(MASListViewItem.Create("Dialogs").WithSubItems(New String() {"Window.Services.Dialogs", "Information / ConfirmAction / Error", "Root-owned dialog float surface"}))
        view.Add(MASListViewItem.Create("Toasts").WithSubItems(New String() {"Window.Services.Toasts", "Info / Success / Warning / Failure / ClearAll", "Root-owned toast float service"}))
        view.Add(MASListViewItem.Create("Tooltips").WithSubItems(New String() {"Window.Services.Tooltips", "Register(control) / Clear", "Root-owned tooltip runtime"}))
        view.Add(MASListViewItem.Create("ContextMenus").WithSubItems(New String() {"Window.Services.ContextMenus", "Register(region, MASDropDownMenuBuilder) / Clear", "Root-owned context-menu coordinator"}))
        view.Add(MASListViewItem.Create("Callout / Popover").WithSubItems(New String() {"Window.Controls.AddCallout(...) / CreatePopover(...)", "Help and hint surfaces use the official callout/popover gateways; no popup service is created in Showcase."}))
        view.Add(MASListViewItem.Create("Drawer / SidePanel").WithSubItems(New String() {"Window.Controls.CreateDrawer(...) / MASSidePanel", "Panel content is MAS child content hosted by the official drawer route; no native panel or overlay path."}))
        view.Add(MASListViewItem.Create("Progress").WithSubItems(New String() {"Window.Services.Progress", "ShowOperation / MASApplicationProgressHandle.Update / Close", "Passive root-owned operation float"}))
        view.Add(MASListViewItem.Create("FilePicker").WithSubItems(New String() {"Window.Services.FilePicker", "ShowOpenFile / ShowPickFolder / Close", "Hosted MAS file-picker float"}))
        view.Add(MASListViewItem.Create("FileExplorer").WithSubItems(New String() {"Window.Services.FileExplorer", "ShowComputer / Close", "Hosted MAS file-explorer float"}))
        view.Add(MASListViewItem.Create("Embedded file controls").WithSubItems(New String() {"Window.Controls", "AddFileDropZone / AddFilePickerControl / AddFileExplorerView", "Shown separately on File surfaces page"}))
    End Sub

    Private Shared Sub PopulateVirtualizationConsumerRows(view As MASListView)
        view.Add(MASListViewItem.Create("MASListBox").WithSubItems(New String() {"Vertical item range, selection, ensure-visible readiness."}))
        view.Add(MASListViewItem.Create("MASListView").WithSubItems(New String() {"Details/tile/list surfaces with measured scrolling."}))
        view.Add(MASListViewItem.Create("MASTreeView").WithSubItems(New String() {"Expanded projection, indentation, focus, scroll-to-node readiness."}))
        view.Add(MASListViewItem.Create("MASTileBox").WithSubItems(New String() {"Measured tile cells for larger visual galleries."}))
        view.Add(MASListViewItem.Create("MASDataGrid").WithSubItems(New String() {"Row virtualization and wide-column viewport behavior."}))
        view.Add(MASListViewItem.Create("DropDownList").WithSubItems(New String() {"Popup item range without handwritten dropdown geometry."}))
        view.Add(MASListViewItem.Create("FileExplorer").WithSubItems(New String() {"Large directory surfaces with identity-based scrolling."}))
    End Sub

    Private Shared Sub PopulateVirtualizationProofRows(view As MASListView, itemCount As Integer)
        If view Is Nothing Then Return
        Dim safeCount As Integer = Math.Max(0, itemCount)
        Dim rows As New List(Of MASListViewItem)(safeCount)
        For index As Integer = 1 To safeCount
            Dim status As String = If(index Mod 17 = 0, "Recycled", "Ready")
            Dim note As String = If(index Mod 29 = 0, "Cache invalidation candidate", "Virtualized public row " & index.ToString(CultureInfo.InvariantCulture))
            rows.Add(MASListViewItem.Create(index.ToString("000000", CultureInfo.InvariantCulture)).WithSubItems(New String() {status, note}))
        Next
        view.ClearItems()
        view.AddRange(rows)
    End Sub

    Private Shared Function CreateSizeProfileSegments(window As MASApplicationWindow) As MASSegmentEntry()
        Dim entries As New List(Of MASSegmentEntry)()
        If window IsNot Nothing Then
            Dim profiles As IReadOnlyList(Of MASSizeProfile) = window.Sizing.GetAll()
            If profiles IsNot Nothing Then
                For Each profile As MASSizeProfile In profiles
                    If profile Is Nothing Then Continue For
                    Dim id As String = profile.Kind.ToString()
                    entries.Add(New MASSegmentEntry(id, BuildSizeProfileDisplayText(profile.Kind)))
                Next
            End If
        End If

        If entries.Count = 0 Then
            Dim values As Array = [Enum].GetValues(GetType(MASSizeProfileKind))
            For Each raw As Object In values
                Dim value As MASSizeProfileKind = CType(raw, MASSizeProfileKind)
                entries.Add(New MASSegmentEntry(value.ToString(), BuildSizeProfileDisplayText(value)))
            Next
        End If

        Return entries.ToArray()
    End Function

    Private Shared Function BuildSizeProfileDisplayText(kind As MASSizeProfileKind) As String
        Return kind.ToString().Replace("TouchFriendly", "Touch Friendly")
    End Function

    Private Shared Function ResolveSizeSegmentId(window As MASApplicationWindow) As String
        If window Is Nothing Then Return MASSizeProfileKind.[Default].ToString()
        Return window.Sizing.CurrentKind.ToString()
    End Function

    Private Shared Function ResolveSizeProfileKind(segmentId As String) As MASSizeProfileKind
        Dim parsed As MASSizeProfileKind
        If [Enum].TryParse(Of MASSizeProfileKind)(If(segmentId, String.Empty).Trim(), True, parsed) Then
            Return parsed
        End If
        Return MASSizeProfileKind.[Default]
    End Function

    Private Shared Function BuildSizingStatusText(window As MASApplicationWindow) As String
        If window Is Nothing Then Return "Current size profile: unavailable"
        Return "Current size profile: " & window.Sizing.CurrentKind.ToString() & "  |  Global profile: " & window.Sizing.IsGlobalApplicationSizeProfile.ToString()
    End Function

    Private Shared Function BuildThemeStudioStatus(window As MASApplicationWindow) As String
        If window Is Nothing Then Return "Current theme: unavailable"
        Return "Current theme: " & window.Theme.CurrentDisplayName & "  |  id: " & window.Theme.CurrentId & "  |  scope: " & window.Theme.Scope.ToString()
    End Function

End Class
