Option Strict On
Option Explicit On

Imports System
Imports Nexamas.UI.Architecture
Imports Nexamas.UI.Branding
Imports Nexamas.UI.General
Imports Nexamas.UI.Rendering
Imports Nexamas.UI.Theming
Imports Nexamas.UI.TopBar.Theming
Imports Nexamas.UI.Values

Imports SkiaSharp

Namespace Nexamas.UI.Components

    Friend NotInheritable Class TopBarPainter
        Implements IDisposable

        Private ReadOnly _p As MASVisualPrimitivesPainter
        Private ReadOnly _shadow As New MASShadowPainter()
        Private ReadOnly _logo As New MasFalconLogoPainter()

        Private ReadOnly _strokePaint As New SKPaint With {
            .IsAntialias = True,
            .IsDither = True,
            .Style = SKPaintStyle.Stroke,
            .StrokeCap = SKStrokeCap.Round
        }

        Private _cachedStaticTopBarImage As SKImage
        Private _cachedStaticTopBarThemeStamp As Integer = Integer.MinValue
        Private _cachedStaticTopBarDpi As Single = 0.0F
        Private _cachedStaticTopBarRectPx As SKRect = SKRect.Empty
        Private _cachedStaticTopBarTitle As String = Nothing
        Private _cachedStaticTopBarShowLogo As Boolean
        Private _cachedStaticTopBarSurfaceMaterialKey As String = Nothing
        Private _cachedStaticTopBarLeftPx As Single
        Private _cachedStaticTopBarTopPx As Single
        Private _cachedStaticTopBarWidthPx As Integer
        Private _cachedStaticTopBarHeightPx As Integer

        Private _disposed As Boolean

        Friend Sub New(primitives As MASVisualPrimitivesPainter)
            If primitives Is Nothing Then Throw New ArgumentNullException(NameOf(primitives))
            _p = primitives
        End Sub

        Friend Sub Render(canvas As SKCanvas,
                  ctx As MASThemeContext,
                  contract As MASResolvedComponentContract,
                  item As TopBarItem,
                  dpi As Single,
                  Optional timeSeconds As Single = 0.0F)

            If _disposed Then Return
            If canvas Is Nothing OrElse ctx Is Nothing OrElse contract Is Nothing OrElse item Is Nothing Then Return
            If Not item.Enabled Then Return
            If item.BarRectPx.Width <= 1 OrElse item.BarRectPx.Height <= 1 Then Return

            dpi = PixelSnap.SafeDpi(dpi)

            If TryDrawCachedStaticTopBar(canvas, ctx, contract, item, dpi, timeSeconds) Then
                Return
            End If

            RenderStaticTopBarUncached(canvas, ctx, contract, item, dpi, timeSeconds)
        End Sub

        Private Function TryDrawCachedStaticTopBar(canvas As SKCanvas,
                                                   ctx As MASThemeContext,
                                                   contract As MASResolvedComponentContract,
                                                   item As TopBarItem,
                                                   dpi As Single,
                                                   timeSeconds As Single) As Boolean

            If canvas Is Nothing OrElse ctx Is Nothing OrElse contract Is Nothing OrElse item Is Nothing Then Return False
            If item.BarRectPx.Width <= TopBarTokens.MinimumUsablePx OrElse item.BarRectPx.Height <= TopBarTokens.MinimumUsablePx Then Return False

            If Not IsStaticTopBarCacheValid(ctx, item, dpi) Then
                Nexamas.UI.Diagnostics.MASFrameDiagnostics.RecordTopBarStaticCacheMiss()

                If Not RebuildStaticTopBarCache(ctx, contract, item, dpi, timeSeconds) Then
                    Return False
                End If
            Else
                Nexamas.UI.Diagnostics.MASFrameDiagnostics.RecordTopBarStaticCacheHit()
            End If

            If _cachedStaticTopBarImage Is Nothing Then Return False

            canvas.DrawImage(_cachedStaticTopBarImage, _cachedStaticTopBarLeftPx, _cachedStaticTopBarTopPx)
            Return True
        End Function

        Private Function RebuildStaticTopBarCache(ctx As MASThemeContext,
                                                  contract As MASResolvedComponentContract,
                                                  item As TopBarItem,
                                                  dpi As Single,
                                                  timeSeconds As Single) As Boolean

            ClearStaticTopBarCache()

            If ctx Is Nothing OrElse contract Is Nothing OrElse item Is Nothing Then Return False
            If item.BarRectPx.Width <= TopBarTokens.MinimumUsablePx OrElse item.BarRectPx.Height <= TopBarTokens.MinimumUsablePx Then Return False

            Dim padPx As Single = Math.Max(TopBarTokens.StaticCachePadMinPx, TopBarTokens.StaticCachePadDip * PixelSnap.SafeDpi(dpi))
            Dim leftPx As Single = CSng(Math.Floor(CDbl(item.BarRectPx.Left - padPx)))
            Dim topPx As Single = CSng(Math.Floor(CDbl(item.BarRectPx.Top - padPx)))
            Dim rightPx As Single = CSng(Math.Ceiling(CDbl(item.BarRectPx.Right + padPx)))
            Dim bottomPx As Single = CSng(Math.Ceiling(CDbl(item.BarRectPx.Bottom + padPx)))

            Dim widthPx As Integer = Math.Max(1, CInt(Math.Ceiling(CDbl(rightPx - leftPx))))
            Dim heightPx As Integer = Math.Max(1, CInt(Math.Ceiling(CDbl(bottomPx - topPx))))

            Dim localItem As TopBarItem = CloneTopBarItemWithOffset(item, -leftPx, -topPx)

            Dim info As New SKImageInfo(widthPx, heightPx, SKColorType.Bgra8888, SKAlphaType.Premul)

            Using surface As SKSurface = SKSurface.Create(info)
                If surface Is Nothing OrElse surface.Canvas Is Nothing Then Return False

                surface.Canvas.Clear(SKColors.Transparent)
                RenderStaticTopBarUncached(surface.Canvas, ctx, contract, localItem, dpi, timeSeconds)
                surface.Canvas.Flush()

                Dim image As SKImage = surface.Snapshot()
                If image Is Nothing Then Return False

                _cachedStaticTopBarImage = image
            End Using

            _cachedStaticTopBarLeftPx = leftPx
            _cachedStaticTopBarTopPx = topPx
            _cachedStaticTopBarThemeStamp = ctx.ThemeStamp
            _cachedStaticTopBarDpi = dpi
            _cachedStaticTopBarRectPx = item.BarRectPx
            _cachedStaticTopBarTitle = If(item.Title, String.Empty)
            _cachedStaticTopBarShowLogo = item.ShowLogo
            _cachedStaticTopBarSurfaceMaterialKey = MASSurfaceTreatmentMaterialKeyNormalizer.NormalizeForStorage(item.SurfaceMaterialKey)
            _cachedStaticTopBarWidthPx = widthPx
            _cachedStaticTopBarHeightPx = heightPx

            Return True
        End Function

        Private Function IsStaticTopBarCacheValid(ctx As MASThemeContext,
                                                  item As TopBarItem,
                                                  dpi As Single) As Boolean

            If _cachedStaticTopBarImage Is Nothing Then Return False
            If ctx Is Nothing OrElse item Is Nothing Then Return False
            If _cachedStaticTopBarThemeStamp <> ctx.ThemeStamp Then Return False
            If Not NearlyEqual(_cachedStaticTopBarDpi, dpi) Then Return False
            If Not RectsEqual(_cachedStaticTopBarRectPx, item.BarRectPx) Then Return False
            If Not String.Equals(_cachedStaticTopBarTitle, If(item.Title, String.Empty), StringComparison.Ordinal) Then Return False
            If _cachedStaticTopBarShowLogo <> item.ShowLogo Then Return False
            If Not String.Equals(_cachedStaticTopBarSurfaceMaterialKey, MASSurfaceTreatmentMaterialKeyNormalizer.NormalizeForStorage(item.SurfaceMaterialKey), StringComparison.OrdinalIgnoreCase) Then Return False
            If _cachedStaticTopBarWidthPx <= 0 OrElse _cachedStaticTopBarHeightPx <= 0 Then Return False

            Return True
        End Function

        Private Shared Function CloneTopBarItemWithOffset(source As TopBarItem,
                                                          offsetX As Single,
                                                          offsetY As Single) As TopBarItem

            Dim clone As New TopBarItem()
            If source Is Nothing Then Return clone

            clone.Title = source.Title
            clone.Enabled = source.Enabled
            clone.IsHoveringDragZone = source.IsHoveringDragZone
            clone.ShowLogo = source.ShowLogo
            clone.SurfaceMaterialKey = source.SurfaceMaterialKey
            clone.BarRectPx = OffsetRect(source.BarRectPx, offsetX, offsetY)
            clone.DragRectPx = OffsetRect(source.DragRectPx, offsetX, offsetY)
            clone.TitleRectPx = OffsetRect(source.TitleRectPx, offsetX, offsetY)
            clone.LogoRectPx = OffsetRect(source.LogoRectPx, offsetX, offsetY)

            Return clone
        End Function

        Private Shared Function OffsetRect(rect As SKRect,
                                           offsetX As Single,
                                           offsetY As Single) As SKRect

            If rect.IsEmpty Then Return rect

            Return New SKRect(
                rect.Left + offsetX,
                rect.Top + offsetY,
                rect.Right + offsetX,
                rect.Bottom + offsetY)
        End Function

        Private Shared Function RectsEqual(a As SKRect, b As SKRect) As Boolean
            Return NearlyEqual(a.Left, b.Left) AndAlso
                   NearlyEqual(a.Top, b.Top) AndAlso
                   NearlyEqual(a.Right, b.Right) AndAlso
                   NearlyEqual(a.Bottom, b.Bottom)
        End Function

        Private Shared Function NearlyEqual(a As Single, b As Single) As Boolean
            Return Math.Abs(a - b) < 0.001F
        End Function

        Private Sub ClearStaticTopBarCache()
            If _cachedStaticTopBarImage Is Nothing Then Return

            Try
                _cachedStaticTopBarImage.Dispose()
            Catch masCaughtException1 As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowDisposeCleanup(masCaughtException1)
            End Try

            _cachedStaticTopBarImage = Nothing
            _cachedStaticTopBarSurfaceMaterialKey = Nothing
            _cachedStaticTopBarWidthPx = 0
            _cachedStaticTopBarHeightPx = 0
        End Sub

        Private Sub RenderStaticTopBarUncached(canvas As SKCanvas,
                                               ctx As MASThemeContext,
                                               contract As MASResolvedComponentContract,
                                               item As TopBarItem,
                                               dpi As Single,
                                               timeSeconds As Single)

            If _disposed Then Return
            If canvas Is Nothing OrElse ctx Is Nothing OrElse contract Is Nothing OrElse item Is Nothing Then Return

            Dim scope As MASContractRenderScope =
    MASArchitectureRuntime.CreateRenderScopeForComponent(Of MASTopBarComponent)(
        NameOf(TopBarPainter),
        contract,
        MASRenderLayer.Surface,
        MASRenderLayer.Shadow,
        MASRenderLayer.Text)

            scope.RequireAnyLayer(
    MASRenderLayer.Surface,
    MASRenderLayer.Shadow,
    MASRenderLayer.Text)


            If Not item.Enabled Then Return
            If item.BarRectPx.Width <= 1 OrElse item.BarRectPx.Height <= 1 Then Return

            dpi = PixelSnap.SafeDpi(dpi)

            Dim app As IMASAppTheme = ctx.Theme
            If app Is Nothing Then Return

            Dim tbTheme As IMASTopBarTheme = MASAppThemeContracts.Families(app).TopBar
            If tbTheme Is Nothing Then Return

            Dim intensity As MASVisualEffectIntensityProfiles.AcrylicSurfaceIntensityProfile =
                MASVisualEffectIntensityProfiles.ResolveAcrylic(contract.SurfaceFamily)

            Dim ringM As MASSurfaceInteractionRing.Metrics = MASSurfaceInteractionRing.GetMetrics(dpi)
            Dim baseR As SKRect = MASSurfaceInteractionRing.SnapBaseRect(item.BarRectPx, ringM)
            If baseR.Width <= 1 OrElse baseR.Height <= 1 Then Return

            Dim rad As Single = 0.0F

            Dim shSpec As MASLayeredShadowSpec =
                MASShadowResolver.ResolveLayered(contract)

            _shadow.DrawLayeredShadow(
                canvas:=canvas,
                r:=baseR,
                radiusPx:=rad,
                dpi:=dpi,
                shadowBase:=tbTheme.ShadowBase,
                spec:=shSpec
            )

            Dim fx As New MASVisualPrimitivesPainter.BarChromeFxSpec With {
                .TopLift = ColorMath.Mix(
                    tbTheme.BarTopLift,
                    SKColors.White,
                    0.028F + (intensity.TopBandEmphasis * 0.038F)
                ),
                .Sheen = ColorMath.Mix(
                    tbTheme.BarSheen,
                    tbTheme.InnerHighlightBase,
                    0.06F + (intensity.SheenStrength * 0.06F)
                ),
                .Base = tbTheme.BarBase,
                .BottomShade = ColorMath.Mix(
                    tbTheme.BarBottomShade,
                    ColorMath.TowardBlack(tbTheme.BarBottomShade, 0.12F),
                    0.06F + (intensity.BottomAnchorStrength * 0.14F)
                ),
                .InnerHighlightBase = tbTheme.InnerHighlightBase,
                .InnerShadowBase = tbTheme.InnerShadowBase,
                .ShadowBase = tbTheme.ShadowBase,
                .BulgeAlpha = ResolveBulgeAlpha(intensity),
                .SpecularAlpha = ResolveSpecularAlpha(intensity),
                .ShadowAlpha = ResolveShadowAlpha(intensity),
                .SpecularBandHDip = ResolveSpecularBandDip(intensity),
                .SpecularTopPadDip = ResolveSpecularTopPadDip(intensity),
                .ShadowDyDip = 2.6F,
                .ShadowSigmaDip = 4.4F,
                .ShadowCasterHDip = 1.7F
            }

            Dim surfaceMaterialDrawn As Boolean = MASSurfaceMaterialComponentGateway.TryDrawTopBarSurface(
                canvas:=canvas,
                ctx:=ctx,
                boundsPx:=baseR,
                materialKey:=item.SurfaceMaterialKey,
                dpi:=dpi,
                cornerRadiusPx:=0.0F,
                surfaceStrengthLevel:=5,
                borderStrengthLevel:=4,
                frameStrength:=MASSurfaceFrameStrength.Level4)

            If Not surfaceMaterialDrawn Then
                _p.DrawBarChromeFx(
                    canvas:=canvas,
                    r:=baseR,
                    dpi:=dpi,
                    contract:=contract,
                    spec:=fx,
                    radiusOverridePx:=0.0F
                )
            End If

            DrawVerticalGlaze(
                canvas:=canvas,
                barRect:=baseR,
                tbTheme:=tbTheme
            )

            DrawTopAccentStrip(
                canvas:=canvas,
                barRect:=baseR,
                ringM:=ringM,
                dpi:=dpi,
                tbTheme:=tbTheme,
                intensity:=intensity
            )

            DrawSheenVeil(
                canvas:=canvas,
                barRect:=baseR,
                tbTheme:=tbTheme,
                intensity:=intensity
            )

            DrawArchitecturalInnerEdge(
                canvas:=canvas,
                barRect:=baseR,
                ringM:=ringM,
                dpi:=dpi,
                tbTheme:=tbTheme,
                intensity:=intensity
            )

            DrawBottomSeparator(canvas, baseR, ringM, dpi, tbTheme, intensity)

            If item.ShowLogo Then
                DrawCenteredLogo(canvas, item, ringM)
            Else
                DrawTitle(canvas, ctx, item, ringM, dpi, tbTheme, intensity)
            End If
        End Sub

        Private Sub DrawCenteredLogo(canvas As SKCanvas,
                             item As TopBarItem,
                             ringM As MASSurfaceInteractionRing.Metrics)

            If canvas Is Nothing Then Return
            If item Is Nothing Then Return

            Dim r0 As SKRect = item.LogoRectPx
            If r0.Width <= 1.0F OrElse r0.Height <= 1.0F Then Return

            Dim r As SKRect = MASSurfaceInteractionRing.SnapBaseRect(r0, ringM)
            If r.Width <= 1.0F OrElse r.Height <= 1.0F Then Return

            _logo.Draw(canvas, r)
        End Sub

        Private Sub DrawVerticalGlaze(canvas As SKCanvas,
                                      barRect As SKRect,
                                      tbTheme As IMASTopBarTheme)

            If canvas Is Nothing Then Return
            If barRect.Width <= 1.0F OrElse barRect.Height <= 1.0F Then Return

            Using glazePaint As New SKPaint()
                glazePaint.IsAntialias = True
                glazePaint.IsDither = True

                Dim topCol As SKColor =
                    ColorMath.Mix(tbTheme.BarTopLift, SKColors.White, 0.06F)

                Dim midCol As SKColor = tbTheme.BarBase

                Dim botCol As SKColor =
                    ColorMath.Mix(tbTheme.BarBottomShade, tbTheme.ShadowBase, 0.08F)

                glazePaint.Shader =
                    SKShader.CreateLinearGradient(
                        New SKPoint(0.0F, barRect.Top),
                        New SKPoint(0.0F, barRect.Bottom),
                        New SKColor() {topCol, midCol, botCol},
                        New Single() {0.0F, 0.5F, 1.0F},
                        SKShaderTileMode.Clamp
                    )

                canvas.DrawRect(barRect, glazePaint)
            End Using
        End Sub

        Private Sub DrawTopAccentStrip(canvas As SKCanvas,
                                       barRect As SKRect,
                                       ringM As MASSurfaceInteractionRing.Metrics,
                                       dpi As Single,
                                       tbTheme As IMASTopBarTheme,
                                       intensity As MASVisualEffectIntensityProfiles.AcrylicSurfaceIntensityProfile)

            If canvas Is Nothing Then Return
            If barRect.Width <= 1.0F OrElse barRect.Height <= 1.0F Then Return

            Dim h As Single = Math.Max(1.0F, (1.1F + (intensity.TopBandEmphasis * 0.9F)) * dpi)
            Dim y0 As Single = barRect.Top
            Dim y1 As Single = PixelSnap.Snap(barRect.Top + h, ringM.SnapStepPx)

            Dim accentCol As SKColor =
                ColorMath.Mix(tbTheme.BarSheen, SKColors.White, 0.22F).WithAlpha(CByte(150))

            Using accentPaint As New SKPaint()
                accentPaint.IsAntialias = True
                accentPaint.Color = accentCol
                canvas.DrawRect(New SKRect(barRect.Left, y0, barRect.Right, y1), accentPaint)
            End Using
        End Sub

        Private Sub DrawSheenVeil(canvas As SKCanvas,
                                  barRect As SKRect,
                                  tbTheme As IMASTopBarTheme,
                                  intensity As MASVisualEffectIntensityProfiles.AcrylicSurfaceIntensityProfile)

            If canvas Is Nothing Then Return
            If barRect.Width <= 1.0F OrElse barRect.Height <= 1.0F Then Return

            Dim sheenH As Single = Math.Max(6.0F, barRect.Height * (0.34F + (intensity.SheenStrength * 0.06F)))

            Dim sheenTop As SKColor =
                ColorMath.Mix(tbTheme.BarSheen, SKColors.White, 0.08F).WithAlpha(CByte(102))

            Using sheenPaint As New SKPaint()
                sheenPaint.IsAntialias = True
                sheenPaint.IsDither = True
                sheenPaint.Shader =
                    SKShader.CreateLinearGradient(
                        New SKPoint(0.0F, barRect.Top),
                        New SKPoint(0.0F, barRect.Top + sheenH),
                        New SKColor() {
                            sheenTop,
                            SKColors.Transparent
                        },
                        New Single() {0.0F, 1.0F},
                        SKShaderTileMode.Clamp
                    )

                canvas.DrawRect(
                    New SKRect(barRect.Left, barRect.Top, barRect.Right, barRect.Top + sheenH),
                    sheenPaint
                )
            End Using
        End Sub

        Private Sub DrawArchitecturalInnerEdge(canvas As SKCanvas,
                                               barRect As SKRect,
                                               ringM As MASSurfaceInteractionRing.Metrics,
                                               dpi As Single,
                                               tbTheme As IMASTopBarTheme,
                                               intensity As MASVisualEffectIntensityProfiles.AcrylicSurfaceIntensityProfile)

            If canvas Is Nothing Then Return
            If barRect.Width <= 1.0F OrElse barRect.Height <= 1.0F Then Return

            Dim insetY As Single = ResolveInnerEdgeInsetDip(intensity) * dpi
            Dim yTop As Single = PixelSnap.Snap(barRect.Top + insetY, ringM.SnapStepPx)

            Dim topAlpha As Integer = CInt(Math.Round(14.0F + (intensity.TopBandEmphasis * 8.0F) + (intensity.SheenStrength * 6.0F)))
            topAlpha = Math.Max(0, Math.Min(255, topAlpha))

            If topAlpha > 0 Then
                _strokePaint.StrokeWidth = Math.Max(1.0F, 1.0F * dpi)
                _strokePaint.Color = ColorMath.Mix(
                    tbTheme.InnerHighlightBase,
                    SKColors.White,
                    0.12F
                ).WithAlpha(CByte(topAlpha))

                canvas.DrawLine(barRect.Left, yTop, barRect.Right, yTop, _strokePaint)
            End If

            Dim bottomInset As Single = Math.Max(1.2F * dpi, 1.0F)
            Dim yBot As Single = PixelSnap.Snap(barRect.Bottom - bottomInset, ringM.SnapStepPx)

            Dim botAlpha As Integer = CInt(Math.Round(13.0F + (intensity.BottomAnchorStrength * 8.0F)))
            botAlpha = Math.Max(0, Math.Min(255, botAlpha))

            If botAlpha > 0 Then
                _strokePaint.StrokeWidth = Math.Max(1.0F, 1.0F * dpi)
                _strokePaint.Color = ColorMath.Mix(
                    tbTheme.InnerShadowBase,
                    tbTheme.ShadowBase,
                    0.18F
                ).WithAlpha(CByte(botAlpha))

                canvas.DrawLine(barRect.Left, yBot, barRect.Right, yBot, _strokePaint)
            End If
        End Sub

        Private Sub DrawBottomSeparator(canvas As SKCanvas,
                                        barRect As SKRect,
                                        ringM As MASSurfaceInteractionRing.Metrics,
                                        dpi As Single,
                                        tbTheme As IMASTopBarTheme,
                                        intensity As MASVisualEffectIntensityProfiles.AcrylicSurfaceIntensityProfile)

            If canvas Is Nothing Then Return
            If barRect.Width <= 1.0F OrElse barRect.Height <= 1.0F Then Return

            Dim a As Integer = TopBarTokens.BottomSeparatorAlpha
            a = CInt(Math.Round(a * (0.9F + (intensity.InnerBorderStrength * 0.22F) + (intensity.BottomAnchorStrength * 0.08F))))
            a = Math.Max(0, Math.Min(255, a))

            If a = 0 Then Return

            Dim h As Single = Math.Max(1.0F, TopBarTokens.BottomSeparatorH * dpi)
            h *= CSng(0.98F + (intensity.InnerBorderStrength * 0.08F))

            Dim y As Single = barRect.Bottom - (h / 2.0F)
            y = PixelSnap.Snap(y, ringM.SnapStepPx)

            _strokePaint.StrokeWidth = h
            _strokePaint.Color = ColorMath.Mix(
                tbTheme.BottomSeparator,
                tbTheme.ShadowBase,
                0.05F
            ).WithAlpha(CByte(a))

            Dim insetX As Single = Math.Max(0.0F, TopBarTokens.BottomSeparatorInsetX * dpi)
            canvas.DrawLine(barRect.Left + insetX, y, barRect.Right - insetX, y, _strokePaint)
        End Sub

        Private Sub DrawTitle(canvas As SKCanvas,
                              ctx As MASThemeContext,
                              item As TopBarItem,
                              ringM As MASSurfaceInteractionRing.Metrics,
                              dpi As Single,
                              tbTheme As IMASTopBarTheme,
                              intensity As MASVisualEffectIntensityProfiles.AcrylicSurfaceIntensityProfile)

            Dim r0 As SKRect = item.TitleRectPx
            If r0.Width <= 1 OrElse r0.Height <= 1 Then Return

            Dim title As String = If(item.Title, String.Empty).Trim()
            If title.Length = 0 Then Return

            dpi = PixelSnap.SafeDpi(dpi)

            Dim r As SKRect = MASSurfaceInteractionRing.SnapBaseRect(r0, ringM)
            If r.Width <= 2 OrElse r.Height <= 2 Then Return

            Dim aMain As Integer = TopBarTokens.TitleAlpha
            aMain = CInt(Math.Round(aMain * (1.0F + (intensity.TopBandEmphasis * 0.02F))))
            aMain = Math.Max(0, Math.Min(255, aMain))

            Dim col As SKColor =
                ColorMath.Mix(tbTheme.TitleText, tbTheme.InnerHighlightBase, 0.03F).WithAlpha(CByte(aMain))

            Dim aEmb As Integer = TopBarTokens.TitleEmbossAlpha
            aEmb = CInt(Math.Round(aEmb * (0.8F + (intensity.TopBandEmphasis * 0.16F) + (intensity.BottomAnchorStrength * 0.04F))))
            aEmb = Math.Max(0, Math.Min(255, aEmb))

            Dim hiCol As SKColor =
                ColorMath.Mix(tbTheme.TitleText, tbTheme.InnerHighlightBase, 0.52F + (intensity.TopBandEmphasis * 0.06F))

            Dim shCol As SKColor =
                ColorMath.Mix(tbTheme.TitleText, tbTheme.ShadowBase, 0.54F + (intensity.BottomAnchorStrength * 0.06F))

            TypographyTextPrimitives.DrawSingleLineText(
                canvas:=canvas,
                ctx:=ctx,
                text:=title,
                bounds:=r,
                dpi:=dpi,
                style:=Nexamas.UI.Values.MASTypography.MASTextStyle.TopBarTitle,
                color:=col,
                align:=TypographyTextPrimitives.TextAlign.Center,
                drawShadow:=False,
                embossAlpha:=CByte(aEmb),
                embossDyDip:=TopBarTokens.TitleEmbossOffsetY,
                embossHighlight:=hiCol,
                embossShadow:=shCol
            )
        End Sub

        Private Shared Function ResolveBulgeAlpha(intensity As MASVisualEffectIntensityProfiles.AcrylicSurfaceIntensityProfile) As Byte
            Dim a As Integer = CInt(Math.Round(54.0F + (intensity.BodyGlowStrength * 30.0F)))
            Return CByte(Math.Max(0, Math.Min(255, a)))
        End Function

        Private Shared Function ResolveSpecularAlpha(intensity As MASVisualEffectIntensityProfiles.AcrylicSurfaceIntensityProfile) As Byte
            Dim a As Integer = CInt(Math.Round(44.0F + (intensity.SheenStrength * 34.0F)))
            Return CByte(Math.Max(0, Math.Min(255, a)))
        End Function

        Private Shared Function ResolveShadowAlpha(intensity As MASVisualEffectIntensityProfiles.AcrylicSurfaceIntensityProfile) As Byte
            Dim a As Integer = CInt(Math.Round(24.0F + (intensity.BottomAnchorStrength * 14.0F)))
            Return CByte(Math.Max(0, Math.Min(255, a)))
        End Function

        Private Shared Function ResolveSpecularBandDip(intensity As MASVisualEffectIntensityProfiles.AcrylicSurfaceIntensityProfile) As Single
            Return 12.2F + (intensity.SheenHeightMul * 2.8F)
        End Function

        Private Shared Function ResolveSpecularTopPadDip(intensity As MASVisualEffectIntensityProfiles.AcrylicSurfaceIntensityProfile) As Single
            Return 1.0F + (intensity.TopBandEmphasis * 0.65F)
        End Function

        Private Shared Function ResolveInnerEdgeInsetDip(intensity As MASVisualEffectIntensityProfiles.AcrylicSurfaceIntensityProfile) As Single
            Return 1.0F + (intensity.TopBandEmphasis * 0.55F)
        End Function

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

            ClearStaticTopBarCache()

            Try
                _strokePaint.Dispose()
            Catch masCaughtException1 As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowDisposeCleanup(masCaughtException1)
            End Try
            Try
                _shadow.Dispose()
            Catch masCaughtException2 As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowDisposeCleanup(masCaughtException2)
            End Try
            Try
                _logo.Dispose()
            Catch masCaughtException3 As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowDisposeCleanup(masCaughtException3)
            End Try
        End Sub

    End Class

End Namespace
