Option Strict On
Option Explicit On

Imports System
Imports Nexamas.UI.Layout
Imports Nexamas.UI.Theming
Imports Nexamas.UI.Values
Imports SkiaSharp

Namespace Nexamas.UI.Components.DropDownMenu

    ''' <summary>
    ''' Internal responsive metric adapter for dropdown/context menu floating surfaces.
    ''' The existing menu controller and renderer intentionally share one metric DPI so
    ''' render, hit-testing, scroll and submenu bridges remain geometrically identical.
    ''' </summary>
    Friend NotInheritable Class DropDownMenuLayoutPlan
        Friend Shared ReadOnly Thresholds As New MASResponsiveLayoutThresholds(
            fullWidthDip:=MenuTokens.DropDownPanelMaxWidth,
            denseWidthDip:=MenuTokens.DropDownPanelMinWidth,
            compactWidthDip:=132.0F,
            minimalWidthDip:=92.0F,
            fullHeightDip:=260.0F,
            denseHeightDip:=190.0F,
            compactHeightDip:=124.0F,
            minimalHeightDip:=64.0F)

        Friend ReadOnly Property ResponsiveProfile As MASResponsiveLayoutProfile
        Friend ReadOnly Property Dpi As Single
        Friend ReadOnly Property MetricDpi As Single
        Friend ReadOnly Property IsCollapsed As Boolean

        Private Sub New(profile As MASResponsiveLayoutProfile)
            Dim safeProfile As MASResponsiveLayoutProfile = If(profile, MASResponsiveLayoutResolver.FromLogicalSize(MASSizeLayoutIntegrationContext.Empty, SKSize.Empty, MASSize.Default, Thresholds))
            Dim chrome As Single = ClampScale(safeProfile.ChromeScale, 0.64F, 1.22F)
            Dim content As Single = ClampScale(safeProfile.ContentScale, 0.64F, 1.22F)
            Dim gap As Single = ClampScale(safeProfile.GapScale, 0.56F, 1.18F)
            If safeProfile.Mode = MASResponsiveLayoutMode.Collapsed Then
                chrome = Math.Min(chrome, 0.68F)
                content = Math.Min(content, 0.72F)
                gap = Math.Min(gap, 0.6F)
            End If
            Me.ResponsiveProfile = safeProfile
            Me.Dpi = safeProfile.DpiScale
            Me.MetricDpi = safeProfile.DpiScale * Math.Min(chrome, Math.Min(content, gap))
            Me.IsCollapsed = safeProfile.Mode = MASResponsiveLayoutMode.Collapsed
        End Sub

        Friend Shared Function Create(ctx As MASThemeContext,
                                      viewportBoundsPx As SKRect,
                                      sizeIntent As MASSize) As DropDownMenuLayoutPlan
            Return New DropDownMenuLayoutPlan(MASResponsiveLayoutResolver.FromTheme(ctx, viewportBoundsPx, sizeIntent, Thresholds))
        End Function

        Private Shared Function ClampScale(value As Single, minimum As Single, maximum As Single) As Single
            If Single.IsNaN(value) OrElse Single.IsInfinity(value) OrElse value <= 0.0F Then Return 1.0F
            Return Math.Min(maximum, Math.Max(minimum, value))
        End Function
    End Class

End Namespace
