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.DiagnosticsDashboard

    ''' <summary>
    ''' Nexamas UI-owned internal Diagnostics Dashboard display surface.
    ''' </summary>
    ''' <remarks>
    ''' The page consumes MASDiagnosticsDashboardBuilder only. It does not record counters, run benchmarks,
    ''' query controls, walk visual trees, read files, create a telemetry API, or let demo code own diagnostics logic.
    ''' </remarks>
    Friend NotInheritable Class MASDiagnosticsDashboardPage
        Implements IDisposable

        Private Const DialogOwnerKey As String = "MAS.DiagnosticsDashboard.Page"

        Private _window As MASApplicationWindow
        Private _title As MASTitle
        Private _description As MASLabel
        Private _status As MASLabel
        Private _summary As MASLabel
        Private _metrics As MASListView
        Private _details As MASLabel
        Private _ownership As MASLabel
        Private _refresh As MASButton
        Private _snapshot As MASDiagnosticsDashboardSnapshot
        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()
            RefreshDashboardSafely(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)
            RefreshDashboardSafely(showDialogOnFailure:=True)
        End Sub

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

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

            _snapshot = Nothing
            _window = Nothing
        End Sub

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

            _description = _window.Controls.AddLabel(
                "Read-only engineering visibility in product language: this Nexamas UI-owned page aggregates existing PerformanceSystem, VirtualizationSystem, layout-owner, and baseline-benchmark facts. The host only attaches the page; it does not create counters, scan controls, or expose telemetry.",
                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("Diagnostics 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 diagnostics metrics...",
                configure:=Sub(label As MASLabel)
                               label.LabelVariant = MASLabelVariant.Body
                               label.TextRole = MASLabelTextRole.Primary
                               label.MultiLine = True
                               label.WordWrap = True
                           End Sub)
            _summary.WithDefaultSize()

            _metrics = _window.Controls.AddListView(configure:=Sub(view As MASListView)
                                                        view.WithDetailsView()
                                                        view.StandaloneChrome()
                                                        view.AddColumn("Metric", 230.0F)
                                                        view.AddColumn("Value", 120.0F)
                                                        view.AddColumn("Source", 245.0F)
                                                        view.AddColumn("Meaning", 520.0F)
                                                    End Sub)
            _metrics.WithDefaultSize()
            AddHandler _metrics.SelectedIndexChanged, AddressOf HandleSelectionChanged

            _details = _window.Controls.AddLabel("Select a metric to see which Nexamas UI owner supplies it and why the row matters.",
                configure:=Sub(label As MASLabel)
                               label.LabelVariant = MASLabelVariant.Body
                               label.TextRole = MASLabelTextRole.Secondary
                               label.MultiLine = True
                               label.WordWrap = True
                           End Sub)
            _details.WithDefaultSize()

            _ownership = _window.Controls.AddLabel(
                "Boundary: DiagnosticsDashboardSystem displays already-owned facts only. PerformanceSystem owns frame/render/invalidation counters, VirtualizationSystem owns realization facts, layout/application owners supply layout facts, and PerformanceSystem owns baseline benchmark evidence. No public telemetry API is opened.",
                configure:=Sub(label As MASLabel)
                               label.LabelVariant = MASLabelVariant.Caption
                               label.TextRole = MASLabelTextRole.Muted
                               label.MultiLine = True
                               label.WordWrap = True
                           End Sub)
            _ownership.WithDefaultSize()

            _refresh = _window.Controls.AddButton("Refresh diagnostics").AsPrimary()
            _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.DataGridSurface(_metrics)
            presentation.FullWidth(_details, MASSize.FillWidth)
            presentation.FullWidth(_ownership, 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)
            RefreshDashboardSafely(showDialogOnFailure:=True)
        End Sub

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

        Private Sub RefreshDashboardSafely(showDialogOnFailure As Boolean)
            Try
                RefreshDashboard()
            Catch ex As Exception
                SetUnavailableState("The diagnostics dashboard could not be refreshed.", ex)
                If showDialogOnFailure Then ShowPageError("The diagnostics dashboard could not be refreshed.", ex)
            End Try
        End Sub

        Private Sub RefreshDashboard()
            _snapshot = MASDiagnosticsDashboardBuilder.CreateCurrent(CreateHostLayoutSnapshot())
            PopulateRows()
            UpdateSummary()
            SelectFirstRowIfNeeded()
        End Sub

        Private Shared Function CreateHostLayoutSnapshot() As MASDiagnosticsDashboardLayoutSnapshot
            Return MASDiagnosticsDashboardLayoutSnapshot.FromCounts(
                layoutPassCount:=0L,
                elementCount:=8,
                ownerName:="MASDiagnosticsDashboardPageHost")
        End Function

        Private Sub PopulateRows()
            If _metrics Is Nothing Then Return

            _metrics.ClearItems()
            If _snapshot Is Nothing Then Return

            For Each metric As MASDiagnosticsDashboardMetric In _snapshot.Metrics
                If metric Is Nothing Then Continue For

                Dim statusText As String = If(metric.IsWarning, "Warning", If(metric.IsAvailable, "Ready", "Unavailable"))
                Dim item As MASListViewItem = MASListViewItem.Create(metric.Title).WithSubItems(New String() {
                    metric.DisplayValue,
                    metric.SourceName,
                    statusText & " — " & metric.Description
                })
                item.Tag = metric
                _metrics.Add(item)
            Next
        End Sub

        Private Sub UpdateSummary()
            If _snapshot Is Nothing Then
                SetUnavailableState("No diagnostics snapshot is available.", Nothing)
                Return
            End If

            Dim readiness As String = If(_snapshot.ReadyForBaselineAwareDisplay,
                                         "baseline-aware display ready",
                                         If(_snapshot.ReadyForReadOnlyDisplay, "read-only display ready", "partial metrics available"))
            _status.Text = "Diagnostics status: " & readiness
            _summary.Text = "Rows: " & _snapshot.MetricCount.ToString(CultureInfo.InvariantCulture) &
                " | Warnings: " & _snapshot.WarningMetricCount.ToString(CultureInfo.InvariantCulture) &
                " | Render: " & ResolveAvailability(_snapshot.HasRenderMetrics) &
                " | Layout: " & ResolveAvailability(_snapshot.HasLayoutMetrics) &
                " | Virtualization: " & ResolveAvailability(_snapshot.HasVirtualizationMetrics) &
                " | Baseline: " & ResolveAvailability(_snapshot.HasBaselineBenchmarkMetrics)
        End Sub

        Private Sub SelectFirstRowIfNeeded()
            If _metrics Is Nothing OrElse _snapshot Is Nothing OrElse _snapshot.MetricCount = 0 Then
                If _details IsNot Nothing Then _details.Text = "No diagnostics metrics are available."
                Return
            End If

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

        Private Sub UpdateDetailsFromSelection()
            If _metrics Is Nothing Then Return
            Dim selected As MASListViewItem = _metrics.SelectedItem
            Dim metric As MASDiagnosticsDashboardMetric = If(selected Is Nothing, Nothing, TryCast(selected.Tag, MASDiagnosticsDashboardMetric))
            If metric Is Nothing Then
                _details.Text = "Select a metric to see which Nexamas UI owner supplies it and why the row matters."
                Return
            End If

            _details.Text = metric.Title & " — " & metric.DisplayValue & Environment.NewLine & Environment.NewLine &
                "Source owner: " & metric.SourceName & Environment.NewLine &
                "Available: " & metric.IsAvailable.ToString() & " | Warning: " & metric.IsWarning.ToString() & Environment.NewLine & Environment.NewLine &
                metric.Description & Environment.NewLine & Environment.NewLine &
                "The host called MASDiagnosticsDashboard.AttachDashboard only; metric contracts and aggregation remain inside Nexamas.UI."
        End Sub

        Private Sub SetUnavailableState(message As String, ex As Exception)
            If _status IsNot Nothing Then _status.Text = "Diagnostics 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 diagnostics dashboard is unavailable.") & detail
            End If
            If _details IsNot Nothing Then _details.Text = "The Diagnostics Dashboard kept ownership inside Nexamas UI and did not fall back to demo-owned telemetry 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 Diagnostics Dashboard could not complete the requested action."),
                        title:="Nexamas UI Diagnostics Dashboard",
                        detail:=If(ex Is Nothing, String.Empty, ex.Message),
                        ownerKey:=DialogOwnerKey)
                End If
            Catch dialogException As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowDiagnosticOnly(dialogException, "DiagnosticsDashboard.Page.DialogBoundary")
            End Try
        End Sub

        Private Shared Function ResolveAvailability(available As Boolean) As String
            Return If(available, "yes", "n/a")
        End Function

    End Class

End Namespace
