Option Strict On
Option Explicit On

Imports System
Imports System.Linq
Imports System.Windows.Forms
Imports Nexamas.UI.Application
Imports Nexamas.UI.Components
Imports Nexamas.UI.Controls
Imports Nexamas.UI.Layout

''' <summary>
''' Public-consumer compile and runtime-smoke host for the Batch 4 product-control recipes.
''' The methods below mirror docs/recipes/product-controls.md and use only public APIs.
''' </summary>
Friend Module Program
    <STAThread>
    Public Sub Main(args As String())
        Global.System.Windows.Forms.Application.EnableVisualStyles()
        Global.System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(False)

        Dim smokeMode As Boolean = args IsNot Nothing AndAlso
            args.Any(Function(value As String) String.Equals(value, "--smoke", StringComparison.OrdinalIgnoreCase))

        Global.System.Windows.Forms.Application.Run(New ProductControlRecipeForm(smokeMode))
    End Sub
End Module

Friend NotInheritable Class ProductControlRecipeForm
    Inherits Form

    Private Shared ReadOnly RuntimeRouteIds As String() = New String() {"tree-grid", "kanban", "pivot", "agenda", "dashboard", "master-detail", "app-layout", "split-view"}

    Private ReadOnly _application As MASApplication
    Private ReadOnly _window As MASApplicationWindow
    Private ReadOnly _smokeTimer As Timer
    Private _smokeRouteIndex As Integer

    Public Sub New(smokeMode As Boolean)
        Text = "Nexamas UI Batch 4 Product-Control Recipes"
        Width = 1440
        Height = 940
        MinimumSize = New System.Drawing.Size(1120, 760)
        StartPosition = FormStartPosition.CenterScreen
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi
        Me.DoubleBuffered = True

        _application = MASApplication.Create()
        _window = _application.CreateWindow(owner:=Me)
        Batch4RecipeSnippets.ConfigureRuntimePages(_window)

        If smokeMode Then
            _smokeTimer = New Timer() With {.Interval = 1200}
            AddHandler _smokeTimer.Tick, AddressOf HandleSmokeTick
            _smokeTimer.Start()
        End If
    End Sub

    Private Sub HandleSmokeTick(sender As Object, e As EventArgs)
        If _smokeRouteIndex < RuntimeRouteIds.Length - 1 Then
            _smokeRouteIndex += 1
            _window.Pages.NavigateTo(RuntimeRouteIds(_smokeRouteIndex))
            Return
        End If

        _smokeTimer.Stop()
        Close()
    End Sub

    Protected Overrides Sub OnFormClosed(e As FormClosedEventArgs)
        If _smokeTimer IsNot Nothing Then
            RemoveHandler _smokeTimer.Tick, AddressOf HandleSmokeTick
            _smokeTimer.Dispose()
        End If
        If _window IsNot Nothing Then _window.Dispose()
        If _application IsNot Nothing Then _application.Dispose()
        MyBase.OnFormClosed(e)
    End Sub
End Class

Friend NotInheritable Class Batch4RecipeSnippets
    Private Sub New()
    End Sub

    Public Shared Sub BuildBatch4LandingPage(window As MASApplicationWindow)
        ' Keep the legacy entry point, but route it through the same scroll-safe PageHost
        ' used by the runtime form. Stacking eight heavyweight product controls in one
        ' LayoutPage caused compression and overlap on common DPI and window sizes.
        ConfigureRuntimePages(window)
    End Sub

    ' Recipe: Product.TreeGrid.Basic
    Public Shared Function BuildTreeGrid(window As MASApplicationWindow) As MASTreeGrid
        Dim tree As MASTreeGrid = window.Controls.AddTreeGrid("Customers")

        tree.AddColumn("status", "Status")
        tree.AddColumn("owner", "Owner")
        tree.AddRootRow("north", "North region", New String() {"Active", "Sales"}, expanded:=True)
        tree.AddRootRow("south", "South region", New String() {"Pending", "Support"}, expanded:=True)
        Return tree
    End Function

    ' Recipe: Product.Kanban.Basic
    Public Shared Function BuildKanban(window As MASApplicationWindow) As MASKanbanBoard
        Dim board As MASKanbanBoard = window.Controls.AddKanbanBoard("Work")

        board.AddColumn("todo", "To do").
            AddColumn("doing", "Doing").
            AddColumn("done", "Done")

        board.AddCard("todo", "task-1", "Prepare offer", "Draft pricing page", "Sales")
        board.AddCard("doing", "task-2", "Review docs", "Check public API recipes", "Docs")
        Return board
    End Function

    ' Recipe: Product.PivotTable.Basic
    Public Shared Function BuildPivotTable(window As MASApplicationWindow) As MASPivotTable
        Dim pivot As MASPivotTable = window.Controls.AddPivotTable("Revenue")

        pivot.AddColumn("q1", "Q1").
            AddColumn("q2", "Q2").
            AddRow("north", "North").
            AddRow("south", "South")

        pivot.SetCellValue("north", "q1", 10D)
        pivot.SetCellValue("north", "q2", 20D)
        pivot.SetCellValue("south", "q1", 12D)
        pivot.SelectCell("north", "q1")
        Return pivot
    End Function

    ' Recipe: Product.Agenda.Basic
    Public Shared Function BuildAgenda(window As MASApplicationWindow) As MASAgendaView
        Return window.Controls.AddAgendaView("Agenda")
    End Function

    ' Recipe: Product.Dashboard.Basic
    Public Shared Function BuildDashboard(window As MASApplicationWindow) As MASDashboardGrid
        Dim dashboard As MASDashboardGrid = window.Controls.AddDashboardGrid("Dashboard")
        dashboard.MoveWidget("sales", targetIndex:=0)
        dashboard.ResizeWidget("sales", spanColumns:=2, spanRows:=1)
        Dim snapshot As MASDashboardGridLayoutSnapshot = dashboard.CreateLayoutSnapshot()
        dashboard.RestoreLayoutSnapshot(snapshot)
        Return dashboard
    End Function

    ' Recipe: Product.MasterDetail.Basic
    Public Shared Function BuildMasterDetail(window As MASApplicationWindow) As MASMasterDetailView
        Dim view As MASMasterDetailView = window.Controls.AddMasterDetailView("Customers")

        view.AddItem("customer-1", "Customer 1", "Active", "Customer details", "Open orders and notes", "A")
        view.AddItem("customer-2", "Customer 2", "Waiting", "Follow-up", "Call back this week", "W")
        view.SelectItem("customer-1")
        Dim snapshot As MASMasterDetailViewSnapshot = view.CreateViewSnapshot()
        Return view
    End Function

    ' Recipe: Product.AppLayout.Basic
    Public Shared Function BuildAppLayout(window As MASApplicationWindow) As MASAppLayout
        Dim layout As MASAppLayout = window.Controls.AddAppLayout("Operations")

        layout.NavigationTitle = "Navigation"
        layout.ContentTitle = "Workspace"
        layout.DetailTitle = "Inspector"
        layout.StatusText = "Ready"
        Return layout
    End Function

    ' Recipe: Product.SplitView.Basic
    Public Shared Function BuildSplitView(window As MASApplicationWindow) As MASSplitView
        Dim split As MASSplitView = window.Controls.AddSplitView("SplitView")

        split.LeftPaneTitle = "Navigation"
        split.ContentPaneTitle = "Content"
        split.RightPaneTitle = "Inspector"
        split.LeftPaneRatio = 0.22F
        split.RightPaneRatio = 0.26F
        split.CollapseRight(False)

        Dim snapshot As MASSplitViewLayoutSnapshot = split.CreateLayoutSnapshot()
        split.RestoreLayoutSnapshot(snapshot)
        Return split
    End Function

    ''' <summary>
    ''' Presents one heavyweight product control per official PageHost route. The previous landing page
    ''' stacked eight large product surfaces into one viewport; this navigation model gives every control
    ''' its own measured workspace and vertical scroll budget.
    ''' </summary>
    Public Shared Sub ConfigureRuntimePages(window As MASApplicationWindow)
        If window Is Nothing Then Throw New ArgumentNullException(NameOf(window))

        Dim pages As MASApplicationPageHost = window.Pages
        pages.ClearPages()
        pages.RegisterPage("tree-grid", "TreeGrid", BindProductPage(window, Function(owner) CType(BuildTreeGrid(owner), MASControlBase), 420.0F), "Product controls", "Hierarchical rows and typed columns in a dedicated large surface.")
        pages.RegisterPage("kanban", "Kanban", BindProductPage(window, Function(owner) CType(BuildKanban(owner), MASControlBase), 440.0F), "Product controls", "Columns and cards with room for board interaction and horizontal content.")
        pages.RegisterPage("pivot", "PivotTable", BindProductPage(window, Function(owner) CType(BuildPivotTable(owner), MASControlBase), 420.0F), "Product controls", "Rows, columns, values, and selection in an isolated analytical surface.")
        pages.RegisterPage("agenda", "Agenda", BindProductPage(window, Function(owner) CType(BuildAgenda(owner), MASControlBase), 440.0F), "Product controls", "Agenda scheduling surface with a full workspace height budget.")
        pages.RegisterPage("dashboard", "DashboardGrid", BindProductPage(window, Function(owner) CType(BuildDashboard(owner), MASControlBase), 460.0F), "Product controls", "Dashboard layout snapshots and widget geometry without competition from other controls.")
        pages.RegisterPage("master-detail", "MasterDetail", BindProductPage(window, Function(owner) CType(BuildMasterDetail(owner), MASControlBase), 460.0F), "Product controls", "Master selection and detail content in one focused route.")
        pages.RegisterPage("app-layout", "AppLayout", BindProductPage(window, Function(owner) CType(BuildAppLayout(owner), MASControlBase), 500.0F), "Product controls", "Navigation, workspace, detail, and status regions at an application-scale height.")
        pages.RegisterPage("split-view", "SplitView", BindProductPage(window, Function(owner) CType(BuildSplitView(owner), MASControlBase), 500.0F), "Product controls", "Three-pane split ratios and snapshot restore in a dedicated route.")

        pages.WithNavigationVisible(True).
            WithBreadcrumbVisible(True).
            WithBreadcrumbRootText("Recipe verification").
            WithRegionBackgrounds(True).
            WithRhythm(MASApplicationSurfaceRhythm.Comfortable).
            WithNavigationSize(MASApplicationSurfaceSideSize.Compact)
        pages.Show()
    End Sub

    Private Shared Function BindProductPage(window As MASApplicationWindow,
                                               factory As Func(Of MASApplicationWindow, MASControlBase),
                                               heightOffset As Single) As Action(Of MASApplicationLayoutPageBuilder)
        Return Sub(page As MASApplicationLayoutPageBuilder)
                   Dim control As MASControlBase = factory.Invoke(window)
                   page.Spacing(MASLayoutSpacing.Large)
                   page.FullWidth(control, MASSize.FillWidth.OffsetHeight(heightOffset))
               End Sub
    End Function

End Class
