﻿Option Strict On
Option Explicit On

Imports System
Imports System.Collections.Generic
Imports Nexamas.UI.Application
Imports Nexamas.UI.Controls
Imports Nexamas.UI.Layout

Partial Friend Class NexamasUIShowcase

    ''' <summary>
    ''' Builds the canonical scenario selected by both a direct capability route
    ''' and a guided journey step. There is one active scenario registry, so the
    ''' two navigation surfaces cannot silently drift apart.
    ''' </summary>
    Private Function BuildSharedScenario(page As MASApplicationLayoutPageBuilder,
                                         routeId As String,
                                         scenarioKey As String) As Boolean
        If page Is Nothing OrElse Window Is Nothing Then Return False

        Dim normalizedRouteId As String = If(routeId, String.Empty).Trim()
        Dim normalizedScenarioKey As String = If(scenarioKey, String.Empty).Trim()
        If normalizedRouteId.Length = 0 OrElse normalizedScenarioKey.Length = 0 Then Return False
        If Not IsSharedScenarioRegisteredForRoute(normalizedRouteId, normalizedScenarioKey) Then Return False

        Dim handled As Boolean = True
        BeginGuidedStageSmartLayout()
        Try
            If IsCanonicalDirectScenarioKey(normalizedScenarioKey) Then
                BuildCanonicalDirectRouteScenario(page, normalizedRouteId)
            Else
                Select Case normalizedScenarioKey
                    Case "controls.text"
                        BuildGuidedStageControlsTextInputs(page)
                    Case "controls.search"
                        BuildGuidedStageControlsSearchFiltersValues(page)
                    Case "controls.datetime"
                        BuildGuidedStageControlsDateTime(page)
                    Case "controls.feedback"
                        BuildGuidedStageControlsFeedback(page)
                    Case "controls.people"
                        BuildGuidedStageControlsPeopleActivity(page)
                    Case "systems.shell"
                        BuildGuidedStageSystemsShellPageHost(page)
                    Case "systems.layout"
                        BuildGuidedStageSystemsLayoutWorkspace(page)
                    Case "systems.theme"
                        BuildGuidedStageSystemsTheme(page)
                    Case "systems.motion"
                        BuildGuidedStageSystemsMotion(page)
                    Case "systems.output"
                        BuildGuidedStageSystemsOutput(page)
                    Case "data.metrics"
                        BuildGuidedStageDataMetricsDashboard(page)
                    Case "data.filters"
                        BuildGuidedStageDataFilters(page)
                    Case "data.hierarchy"
                        BuildGuidedStageDataHierarchyPivot(page)
                    Case "theme.feedback"
                        BuildGuidedStageThemeFeedback(page)
                    Case "theme.motion"
                        BuildGuidedStageThemeMotion(page)
                    Case "theme.forms"
                        BuildGuidedStageThemeForms(page)
                    Case "theme.output"
                        BuildGuidedStageThemeOutput(page)
                    Case "proof.boundary"
                        BuildGuidedStageProofBoundary(page)
                    Case Else
                        handled = False
                End Select
            End If
        Finally
            EndGuidedStageSmartLayout(page)
        End Try

        Return handled
    End Function

    Private Function IsCanonicalDirectScenarioKey(scenarioKey As String) As Boolean
        Select Case If(scenarioKey, String.Empty).Trim()
            Case "controls.actions"
                Return True
            Case "controls.selection"
                Return True
            Case "controls.lists"
                Return True
            Case "controls.icons"
                Return True
            Case "controls.tiles"
                Return True
            Case "controls.visual"
                Return True
            Case "controls.files"
                Return True
            Case "systems.services"
                Return True
            Case "systems.lifetime"
                Return True
            Case "systems.workflow"
                Return True
            Case "systems.productivity"
                Return True
            Case "systems.sizing"
                Return True
            Case "data.grid"
                Return True
            Case "data.charts"
                Return True
            Case "data.planning"
                Return True
            Case "data.inspector"
                Return True
            Case "data.virtualization"
                Return True
            Case "theme.readability"
                Return True
            Case "theme.material"
                Return True
            Case "theme.localization"
                Return True
            Case "proof.docs"
                Return True
            Case "proof.licensing"
                Return True
            Case "proof.commercial"
                Return True
            Case "proof.coverage"
                Return True
            Case "proof.render"
                Return True
            Case "proof.output"
                Return True
            Case "proof.package"
                Return True
            Case "proof.certification"
                Return True
            Case "proof.diagnostics"
                Return True
            Case "proof.dpiAccessibility"
                Return True
            Case Else
                Return False
        End Select
    End Function

    Private Function IsSharedScenarioRegisteredForRoute(routeId As String,
                                                        scenarioKey As String) As Boolean
        For Each scenario As GuidedJourneyStep In GetSharedRouteScenarioSteps(routeId)
            If scenario IsNot Nothing AndAlso
               String.Equals(scenario.GroupKey, scenarioKey, StringComparison.OrdinalIgnoreCase) Then
                Return True
            End If
        Next
        Return False
    End Function

    Private Sub BuildCanonicalDirectRouteScenario(page As MASApplicationLayoutPageBuilder,
                                                  routeId As String)
        Dim entry As ShowcaseNavigationEntry = ShowcaseNavigationCatalog.FindById(routeId)
        If entry Is Nothing Then
            Throw New InvalidOperationException("Shared Showcase scenario references an unknown route: " & If(routeId, String.Empty))
        End If

        ShowcasePageHostContentBuilder.Build(
            page:=page,
            window:=Window,
            entry:=entry,
            topBar:=ShowcaseTopBar,
            application:=ApplicationFacade,
            registerLifetime:=AddressOf RegisterPageLifetime)
    End Sub

    ''' <summary>
    ''' Resolves a direct capability route through the same scenario registry used
    ''' by focused journeys. Routes with a canonical full-route scenario render it
    ''' once. Routes intentionally split into focused scenarios compose those same
    ''' focused builders in deterministic journey order.
    ''' </summary>
    Private Function BuildSharedRouteScenarios(page As MASApplicationLayoutPageBuilder,
                                               entry As ShowcaseNavigationEntry) As Boolean
        If page Is Nothing OrElse entry Is Nothing Then Return False

        Dim scenarios As IReadOnlyList(Of GuidedJourneyStep) = GetSharedRouteScenarioSteps(entry.Id)
        If scenarios.Count = 0 Then Return False

        Dim canonicalScenario As GuidedJourneyStep = Nothing
        For Each scenario As GuidedJourneyStep In scenarios
            If scenario IsNot Nothing AndAlso IsCanonicalDirectScenarioKey(scenario.GroupKey) Then
                If canonicalScenario IsNot Nothing Then
                    Throw New InvalidOperationException("Route '" & entry.Id & "' has more than one canonical shared scenario.")
                End If
                canonicalScenario = scenario
            End If
        Next

        If canonicalScenario IsNot Nothing Then
            Return BuildSharedScenario(page, canonicalScenario.RouteId, canonicalScenario.GroupKey)
        End If

        Dim showSectionHeaders As Boolean = scenarios.Count > 1
        For Each scenario As GuidedJourneyStep In scenarios
            If scenario Is Nothing Then Continue For

            If showSectionHeaders Then
                Dim sectionTitle = Window.Controls.AddTitle(scenario.Title)
                AddShowcaseContent(page, sectionTitle, MASSize.HugContent)
                AddShowcaseContent(page, CreateMuted(scenario.Message), MASSize.FillWidth)
            End If

            If Not BuildSharedScenario(page, scenario.RouteId, scenario.GroupKey) Then
                Dim failure As MASStatusBanner = Window.Controls.AddStatusBanner(
                    title:="Scenario mapping unavailable",
                    message:="Route '" & entry.Id & "' could not resolve shared scenario '" & scenario.GroupKey & "'. The build-time route matrix gate must reject this state.",
                    tone:=MASToastTone.Danger)
                failure.WithSize(MASSize.FillWidth)
                AddShowcaseContent(page, failure, MASSize.FillWidth)
            End If
        Next

        Return True
    End Function

    Private Function GetSharedRouteScenarioSteps(routeId As String) As IReadOnlyList(Of GuidedJourneyStep)
        Dim result As New List(Of GuidedJourneyStep)()
        Dim seenScenarioKeys As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)
        Dim normalizedRouteId As String = If(routeId, String.Empty).Trim()
        If normalizedRouteId.Length = 0 Then Return result.AsReadOnly()

        For Each journeyId As String In New String() {"controls", "systems", "data", "theme", "proof"}
            Dim journey As GuidedJourneyDefinition = ResolveGuidedJourney(journeyId)
            If journey Is Nothing OrElse journey.Steps Is Nothing Then Continue For

            For Each scenario As GuidedJourneyStep In journey.Steps
                If scenario Is Nothing Then Continue For
                If Not String.Equals(scenario.RouteId, normalizedRouteId, StringComparison.OrdinalIgnoreCase) Then Continue For
                If seenScenarioKeys.Add(scenario.GroupKey) Then result.Add(scenario)
            Next
        Next

        Return result.AsReadOnly()
    End Function

End Class
