Option Strict On
Option Explicit On

Imports System.Collections.Generic
Imports System.Collections.ObjectModel

Namespace Nexamas.UI.Quality

    ''' <summary>
    ''' Central manifest for the remaining control-specific production gaps. This is
    ''' intentionally separate from the readiness matrix so that CompactPreview
    ''' controls can carry explicit, auditable blockers without pretending those
    ''' blockers are already closed.
    ''' </summary>
    Friend NotInheritable Class MASControlProductionGapManifest

        Private Const ExpectedProductControlCount As Integer = 8
        Private ReadOnly _records As IReadOnlyList(Of MASControlProductionGapRecord)

        Private Sub New(records As IEnumerable(Of MASControlProductionGapRecord))
            Dim normalized As New List(Of MASControlProductionGapRecord)()
            If records IsNot Nothing Then
                For Each record As MASControlProductionGapRecord In records
                    If record IsNot Nothing Then normalized.Add(record)
                Next
            End If
            _records = New ReadOnlyCollection(Of MASControlProductionGapRecord)(normalized.ToArray())
        End Sub

        Friend ReadOnly Property Records As IReadOnlyList(Of MASControlProductionGapRecord)
            Get
                Return _records
            End Get
        End Property

        Friend ReadOnly Property Count As Integer
            Get
                Return _records.Count
            End Get
        End Property

        Friend ReadOnly Property HasExpectedProductControlCoverage As Boolean
            Get
                Return ComponentCount() = ExpectedProductControlCount AndAlso
                       HasGapCoverageFor("treegrid") AndAlso
                       HasGapCoverageFor("pivottable") AndAlso
                       HasGapCoverageFor("kanban") AndAlso
                       HasGapCoverageFor("agenda") AndAlso
                       HasGapCoverageFor("dashboardgrid") AndAlso
                       HasGapCoverageFor("masterdetail") AndAlso
                       HasGapCoverageFor("applayout") AndAlso
                       HasGapCoverageFor("splitview")
            End Get
        End Property

        Friend Function HasGapCoverageFor(componentId As String) As Boolean
            Return FindByComponent(componentId).Count > 0
        End Function

        Friend Function FindByComponent(componentId As String) As IReadOnlyList(Of MASControlProductionGapRecord)
            Dim normalized As String = If(componentId, String.Empty).Trim()
            Dim matches As New List(Of MASControlProductionGapRecord)()
            If normalized.Length = 0 Then Return New ReadOnlyCollection(Of MASControlProductionGapRecord)(matches)

            For Each record As MASControlProductionGapRecord In _records
                If record IsNot Nothing AndAlso String.Equals(record.ComponentId, normalized, System.StringComparison.OrdinalIgnoreCase) Then
                    matches.Add(record)
                End If
            Next

            Return New ReadOnlyCollection(Of MASControlProductionGapRecord)(matches)
        End Function

        Friend Function HasOpenGapFor(componentId As String) As Boolean
            For Each record As MASControlProductionGapRecord In FindByComponent(componentId)
                If record IsNot Nothing AndAlso Not record.IsClosed Then Return True
            Next
            Return False
        End Function

        Friend Function AllGapsClosedFor(componentId As String) As Boolean
            Dim records As IReadOnlyList(Of MASControlProductionGapRecord) = FindByComponent(componentId)
            If records.Count = 0 Then Return False

            For Each record As MASControlProductionGapRecord In records
                If record Is Nothing OrElse Not record.IsClosed OrElse Not record.HasClosureEvidence Then Return False
            Next

            Return True
        End Function

        Private Function ComponentCount() As Integer
            Dim ids As New HashSet(Of String)(System.StringComparer.OrdinalIgnoreCase)
            For Each record As MASControlProductionGapRecord In _records
                If record IsNot Nothing AndAlso record.ComponentId.Length > 0 Then ids.Add(record.ComponentId)
            Next
            Return ids.Count
        End Function

        Friend Shared Function CreateDefault() As MASControlProductionGapManifest
            Dim records As New List(Of MASControlProductionGapRecord)()

            AddGap(records, "treegrid", "TreeGrid", "treegrid-writeback-adapters", MASControlProductionGapCategory.DataBinding, "Source write-back adapters", "Closed by Friend-only TreeGrid source write-back adapter proof for label/value edits over MASListItemsSource with validation through normalized row/cell text and failure semantics that keep unsupported sources detached from public adapter exposure.", "TreeGrid.WriteBackAdapters", 1, MASControlProductionGapStatus.Closed)
            AddGap(records, "treegrid", "TreeGrid", "treegrid-incremental-updates", MASControlProductionGapCategory.Performance, "Incremental source updates", "Closed by incremental add/remove/replace source-change proof preserving selection, expanded state, source revision, bounded row-window behavior, and avoiding full source reprojection for supported MASListItemsSource deltas.", "TreeGrid.IncrementalUpdates", 2, MASControlProductionGapStatus.Closed)
            AddGap(records, "treegrid", "TreeGrid", "treegrid-final-promotion-pass", MASControlProductionGapCategory.Documentation, "Final promotion pass", "Closed by targeted TreeGrid ProductionReady promotion: source projection, sort/filter, editing lifecycle, bounded row-window proof, Friend-only write-back adapter, incremental source deltas, benchmark baseline/threshold, keyboard/accessibility stress, public adapter non-exposure, docs/sample boundary, final commercial-readiness closure, and release-freeze evidence are all governed.", "TreeGrid.FinalPromotionPass", 3, MASControlProductionGapStatus.Closed)

            AddGap(records, "pivottable", "PivotTable", "pivottable-multilevel-grouping", MASControlProductionGapCategory.DataBinding, "Multi-level grouping policy", "Closed by Friend-only PivotTable multi-level grouping proof that composes row/column hierarchy paths into deterministic display labels and stable drilldown keys before projection, without opening OLAP/query engine or public source-adapter ownership.", "PivotTable.MultiLevelGrouping", 1, MASControlProductionGapStatus.Closed)
            AddGap(records, "pivottable", "PivotTable", "pivottable-export-writers", MASControlProductionGapCategory.Export, "Export writer policy", "Closed by Friend-only PivotTable in-memory delimited export writer policy over MASPivotExportSnapshot; file, clipboard, Excel, PDF, storage, and dialog ownership remain outside the control.", "PivotTable.ExportWriters", 2, MASControlProductionGapStatus.Closed)
            AddGap(records, "pivottable", "PivotTable", "pivottable-final-promotion-pass", MASControlProductionGapCategory.Documentation, "Final promotion pass", "Closed by targeted PivotTable ProductionReady promotion: source projection, aggregation, drilldown/export snapshot, bounded matrix-window proof, deterministic multi-level grouping, in-memory export writer policy, benchmark baseline/threshold, keyboard/accessibility stress, public adapter non-exposure, docs/sample boundary, final commercial-readiness closure, and release-freeze evidence are all governed.", "PivotTable.FinalPromotionPass", 3, MASControlProductionGapStatus.Closed)

            AddGap(records, "kanban", "KanbanBoard", "kanban-wip-drop-rules", MASControlProductionGapCategory.Interaction, "WIP and drop-rule contracts", "Closed by Friend-only Kanban drop-rule snapshot proof: legal targets are accepted, missing cards/columns return rejected-drop feedback, requested indexes are normalized, and pointer/keyboard/public move paths share the same bounded board rule contract.", "Kanban.WipDropRules", 1, MASControlProductionGapStatus.Closed)
            AddGap(records, "kanban", "KanbanBoard", "kanban-writeback-policy", MASControlProductionGapCategory.DataBinding, "Public write-back policy", "Closed by targeted KanbanBoard ProductionReady promotion: public/manual moves intentionally detach from projected sources instead of mutating external task data; source projection stays Friend-only, no public provider/database/write-back adapter is exposed, and task persistence/workflow/background sync remain outside the control.", "Kanban.WriteBackPolicy", 2, MASControlProductionGapStatus.Closed)
            AddGap(records, "kanban", "KanbanBoard", "kanban-final-promotion-pass", MASControlProductionGapCategory.Documentation, "Final promotion pass", "Closed by targeted KanbanBoard ProductionReady promotion: source projection, snapshot/restore, reorder/persistence, WIP/drop-rule proof, intentional source-detach write-back policy, bounded large-board windowing, keyboard/accessibility stress, benchmark baseline/threshold, public adapter non-exposure, docs/sample boundary, final commercial-readiness closure, and release-freeze evidence are all governed.", "Kanban.FinalPromotionPass", 3, MASControlProductionGapStatus.Closed)

            AddGap(records, "agenda", "AgendaView", "agenda-recurrence-timezone", MASControlProductionGapCategory.Scheduling, "Recurrence and time-zone policy", "Closed by Friend-only AgendaView temporal policy proof: the control consumes concrete timestamps, projects deterministic visual day/minute windows across DST-like wall-clock boundaries, keeps recurrence expansion and time-zone databases upstream, and uses deterministic test clocks without opening external calendar providers.", "Agenda.RecurrenceTimeZone", 1, MASControlProductionGapStatus.Closed)
            AddGap(records, "agenda", "AgendaView", "agenda-move-resize-contracts", MASControlProductionGapCategory.Interaction, "Event move/resize contracts", "Closed by Friend-only AgendaView event edit proof: move/resize requests validate bounded visual windows, retain selection, reject invalid windows with feedback, and intentionally detach projected sources instead of mutating external calendars or exposing public provider/write-back APIs.", "Agenda.EventMoveResize", 2, MASControlProductionGapStatus.Closed)
            AddGap(records, "agenda", "AgendaView", "agenda-final-promotion-pass", MASControlProductionGapCategory.Documentation, "Final promotion pass", "Closed by targeted AgendaView ProductionReady promotion: overlap layout, day/week/month range views, source/range windowing, recurrence/time-zone visual boundary policy, Friend-only event move/resize contracts, benchmark baseline/threshold, keyboard/accessibility stress, public adapter non-exposure, docs/sample boundary, final commercial-readiness closure, and release-freeze evidence are all governed.", "Agenda.FinalPromotionPass", 3, MASControlProductionGapStatus.Closed)

            AddGap(records, "dashboardgrid", "DashboardGrid", "dashboard-child-hosting", MASControlProductionGapCategory.Hosting, "Child/widget hosting", "Closed by Friend-only hosted-widget lifecycle contract using MASControlBase RegisterChild/UnregisterChild and MASHostingContractClosureGate evidence.", "DashboardGrid.ChildHosting", 1, MASControlProductionGapStatus.Closed)
            AddGap(records, "dashboardgrid", "DashboardGrid", "dashboard-provider-refresh", MASControlProductionGapCategory.DataBinding, "Widget provider refresh", "Closed by Friend-only provider refresh contract with revision, selected-key preservation, error/recovered states, and MASDashboardProviderMasterDetailStateClosureGate evidence.", "DashboardGrid.ProviderRefresh", 2, MASControlProductionGapStatus.Closed)
            AddGap(records, "dashboardgrid", "DashboardGrid", "dashboard-public-provider-adapter", MASControlProductionGapCategory.DataBinding, "Public provider adapter policy", "Closed by Friend-only provider adapter policy snapshot proving internal projection-only refresh, no public adapter exposure, no external storage ownership, no shell refresh loop, and MASDashboardProviderHostAdoptionClosureGate evidence.", "DashboardGrid.PublicProviderAdapter", 3, MASControlProductionGapStatus.Closed)
            AddGap(records, "dashboardgrid", "DashboardGrid", "dashboard-keyboard-resize-thresholds", MASControlProductionGapCategory.Accessibility, "Production keyboard/a11y resize thresholds", "Closed by Friend-only DashboardGrid keyboard resize threshold snapshot proving bounded spans, hosted-widget state, readable resize text, and bounded widget-window behavior under MaxWidgets layouts.", "DashboardGrid.KeyboardResizeThresholds", 4, MASControlProductionGapStatus.Closed)
            AddGap(records, "dashboardgrid", "DashboardGrid", "dashboard-benchmark-baselines", MASControlProductionGapCategory.Performance, "Benchmark baselines and thresholds", "Closed by product-control benchmark baseline/threshold policy evidence that captures the official DashboardGrid proof path and applies internal Release|x64 guardrails.", "DashboardGrid.BenchmarkBaselines", 5, MASControlProductionGapStatus.Closed)
            AddGap(records, "dashboardgrid", "DashboardGrid", "dashboard-final-promotion-pass", MASControlProductionGapCategory.Documentation, "Final promotion pass", "Closed by targeted DashboardGrid ProductionReady promotion: final commercial-readiness closure, release-freeze evidence, public provider-adapter non-exposure, docs/sample boundary, benchmark baseline/threshold, keyboard/a11y resize thresholds, hosted-widget lifecycle, provider-refresh state, provider-host adoption, and dashboard resize host-sample evidence are all governed.", "DashboardGrid.FinalPromotionPass", 6, MASControlProductionGapStatus.Closed)

            AddGap(records, "masterdetail", "MasterDetailView", "masterdetail-detail-hosting", MASControlProductionGapCategory.Hosting, "Detail hosting contract", "Closed by Friend-only selected-detail lifecycle contract using MASControlBase RegisterChild/UnregisterChild and MASHostingContractClosureGate evidence.", "MasterDetail.DetailHosting", 1, MASControlProductionGapStatus.Closed)
            AddGap(records, "masterdetail", "MasterDetailView", "masterdetail-empty-error-states", MASControlProductionGapCategory.Interaction, "Empty/error state foundation", "Closed by Friend-only empty/error visual state snapshot, source-snapshot failure handling, recovered-normal state proof, and MASDashboardProviderMasterDetailStateClosureGate evidence.", "MasterDetail.EmptyErrorStates", 2, MASControlProductionGapStatus.Closed)
            AddGap(records, "masterdetail", "MasterDetailView", "masterdetail-item-virtualization", MASControlProductionGapCategory.Performance, "Master item virtualization", "Closed by Friend-only bounded master-item window snapshot over 1000 source records with selection, ensure-visible, refresh preservation, and MASMasterDetailSplitViewClosureGate evidence.", "MasterDetail.ItemVirtualization", 3, MASControlProductionGapStatus.Closed)
            AddGap(records, "masterdetail", "MasterDetailView", "masterdetail-routing-public-adapter", MASControlProductionGapCategory.Routing, "Routing/public adapter closure", "Closed by Friend-only routing/public-adapter boundary snapshot proving MasterDetailView remains a visual/source-projection surface and does not own routing, PageHost, native shell, or public adapter exposure.", "MasterDetail.RoutingPublicAdapter", 4, MASControlProductionGapStatus.Closed)

            AddGap(records, "masterdetail", "MasterDetailView", "masterdetail-public-adapter-approval", MASControlProductionGapCategory.DataBinding, "Public adapter approval", "Closed by targeted MasterDetailView ProductionReady promotion: the public boundary is the existing AddMasterDetailView/manual item/snapshot surface plus a permanent visual/source-projection adapter non-exposure policy; Friend-only source projection remains internal and no external write-back/routing adapter is required.", "MasterDetail.PublicAdapterApproval", 5, MASControlProductionGapStatus.Closed)
            AddGap(records, "masterdetail", "MasterDetailView", "masterdetail-final-promotion-pass", MASControlProductionGapCategory.Documentation, "Final promotion pass", "Closed by targeted MasterDetailView ProductionReady promotion: final commercial-readiness closure, release-freeze evidence, adapter non-exposure/non-applicability boundary, docs/sample boundary, benchmark baseline/threshold, keyboard/a11y stress, detail-host lifecycle, empty/error state foundation, bounded item-window proof, source projection, persistence, and routing-shell boundary evidence are all governed.", "MasterDetail.FinalPromotionPass", 6, MASControlProductionGapStatus.Closed)

            AddGap(records, "applayout", "AppLayout", "applayout-child-slot-hosting", MASControlProductionGapCategory.Hosting, "Child-slot hosting", "Closed by Friend-only header/navigation/content/details/status slot lifecycle contract using MASControlBase RegisterChild/UnregisterChild and MASHostingContractClosureGate evidence.", "AppLayout.ChildSlotHosting", 1, MASControlProductionGapStatus.Closed)
            AddGap(records, "applayout", "AppLayout", "applayout-routing-ownership", MASControlProductionGapCategory.Routing, "Route/page ownership", "Closed by Friend-only route/page ownership boundary snapshot proving AppLayout remains a visual slot layout surface and does not own routing, PageHost, native shell, or public adapter exposure.", "AppLayout.RoutingOwnership", 2, MASControlProductionGapStatus.Closed)

            AddGap(records, "applayout", "AppLayout", "applayout-responsive-shell-adoption", MASControlProductionGapCategory.Routing, "Responsive shell adoption proof", "Closed by Friend-only host-adoption snapshot proving AppLayout slot/layout snapshots and responsive breakpoint intent can be consumed by a host while router, PageHost, native shell, persistence, and public adapter ownership remain outside AppLayout.", "AppLayout.ResponsiveShellAdoption", 3, MASControlProductionGapStatus.Closed)
            AddGap(records, "applayout", "AppLayout", "applayout-real-host-adoption", MASControlProductionGapCategory.Routing, "Real application-host adoption", "Closed by Friend-only real host-adoption sample evidence proving compact/wide host scenarios, responsive breakpoint intent, hosted slots, release sample coverage, and external router/PageHost/native shell ownership.", "AppLayout.RealHostAdoptionSample", 4, MASControlProductionGapStatus.Closed)
            AddGap(records, "applayout", "AppLayout", "applayout-benchmark-baselines", MASControlProductionGapCategory.Performance, "Benchmark baselines and thresholds", "Closed by product-control benchmark baseline/threshold policy evidence that captures the official AppLayout proof path and applies internal Release|x64 guardrails.", "AppLayout.BenchmarkBaselines", 5, MASControlProductionGapStatus.Closed)
            AddGap(records, "applayout", "AppLayout", "applayout-final-promotion-pass", MASControlProductionGapCategory.Documentation, "Final promotion pass", "Closed by targeted AppLayout ProductionReady promotion: final commercial-readiness closure, release-freeze evidence, adapter non-applicability, docs/sample boundary, benchmark baseline/threshold, keyboard/a11y stress, hosting, routing-shell, host-adoption, real host-adoption sample, and persistence evidence are all governed.", "AppLayout.FinalPromotionPass", 6, MASControlProductionGapStatus.Closed)

            AddGap(records, "splitview", "SplitView", "splitview-child-content-hosting", MASControlProductionGapCategory.Hosting, "Child-content hosting", "Closed by Friend-only left/content/right pane lifecycle contract using MASControlBase RegisterChild/UnregisterChild and MASHostingContractClosureGate evidence.", "SplitView.ChildContentHosting", 1, MASControlProductionGapStatus.Closed)
            AddGap(records, "splitview", "SplitView", "splitview-keyboard-splitter", MASControlProductionGapCategory.Accessibility, "Production keyboard splitter", "Closed by Friend-only keyboard splitter contract with focused divider state, bounded small/large increments, collapse/expand behavior, and MASMasterDetailSplitViewClosureGate evidence; shell-level announcements remain outside SplitView.", "SplitView.KeyboardSplitter", 2, MASControlProductionGapStatus.Closed)
            AddGap(records, "splitview", "SplitView", "splitview-shell-integration", MASControlProductionGapCategory.Routing, "Shell integration boundary", "Closed by Friend-only shell integration boundary snapshot proving SplitView owns pane ratios/splitter focus only while shell announcements, pane-intent persistence, and host focus coordination remain host responsibilities.", "SplitView.ShellIntegration", 3, MASControlProductionGapStatus.Closed)

            AddGap(records, "splitview", "SplitView", "splitview-host-adoption-proof", MASControlProductionGapCategory.Routing, "Host-level adoption proof", "Closed by Friend-only host-adoption snapshot proving a host can consume SplitView pane/splitter snapshots for persistence intent, focus coordination, and announcements without moving shell ownership into SplitView.", "SplitView.HostAdoptionProof", 4, MASControlProductionGapStatus.Closed)
            AddGap(records, "splitview", "SplitView", "splitview-real-host-adoption", MASControlProductionGapCategory.Routing, "Real host adoption", "Closed by Friend-only real host-adoption sample evidence proving focus handoff, announcement intent, persistence intent, hosted pane lifecycle, and external native shell ownership.", "SplitView.RealHostAdoptionSample", 5, MASControlProductionGapStatus.Closed)
            AddGap(records, "splitview", "SplitView", "splitview-benchmark-baselines", MASControlProductionGapCategory.Performance, "Benchmark baselines and thresholds", "Closed by product-control benchmark baseline/threshold policy evidence that captures the official SplitView proof path and applies internal Release|x64 guardrails.", "SplitView.BenchmarkBaselines", 6, MASControlProductionGapStatus.Closed)
            AddGap(records, "splitview", "SplitView", "splitview-final-promotion-pass", MASControlProductionGapCategory.Documentation, "Final promotion pass", "Closed by targeted SplitView ProductionReady promotion: final commercial-readiness closure, release-freeze evidence, adapter non-applicability, docs/sample boundary, benchmark baseline/threshold, keyboard/a11y stress, hosting, shell, host-adoption, and persistence evidence are all governed.", "SplitView.FinalPromotionPass", 7, MASControlProductionGapStatus.Closed)

            Return New MASControlProductionGapManifest(records)
        End Function

        Private Shared Sub AddGap(records As List(Of MASControlProductionGapRecord),
                                  componentId As String,
                                  componentName As String,
                                  gapId As String,
                                  category As MASControlProductionGapCategory,
                                  title As String,
                                  closureCondition As String,
                                  evidenceKey As String,
                                  priority As Integer,
                                  Optional status As MASControlProductionGapStatus = MASControlProductionGapStatus.Planned)
            records.Add(New MASControlProductionGapRecord(componentId,
                                                          componentName,
                                                          gapId,
                                                          category,
                                                          status,
                                                          title,
                                                          closureCondition,
                                                          evidenceKey,
                                                          priority))
        End Sub

    End Class

End Namespace
