Option Strict On
Option Explicit On

Imports System
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Windows.Forms
Imports Nexamas.UI.Controls
Imports Nexamas.UI.Theming
Imports Nexamas.UI.Values
Imports SkiaSharp

Namespace Nexamas.UI.Components

    ''' <summary>
    ''' Friend-owned policy for MASMetricCard. It centralizes display text hygiene,
    ''' tone normalization, compact layout decisions, sparkline sample normalization,
    ''' and explicit boundaries so the card does not become a metric store,
    ''' analytics collector, telemetry pipe, live-refresh loop, chart engine, or
    ''' dashboard composition system.
    ''' </summary>
    Friend NotInheritable Class MASMetricCardPolicy
        Private Sub New()
        End Sub

        Friend Const MaxTitleLength As Integer = 96
        Friend Const MaxValueLength As Integer = 64
        Friend Const MaxSubtitleLength As Integer = 160
        Friend Const MaxTrendLength As Integer = 64
        Friend Const MaxSparklineSamples As Integer = 48

        Friend Shared Function NormalizeTitle(value As String) As String
            Dim text As String = NormalizeText(value, MaxTitleLength)
            If text.Length = 0 Then Return MetricCardTokens.DefaultTitle
            Return text
        End Function

        Friend Shared Function NormalizeValueText(value As String) As String
            Dim text As String = NormalizeText(value, MaxValueLength)
            If text.Length = 0 Then Return MetricCardTokens.DefaultValueText
            Return text
        End Function

        Friend Shared Function NormalizeSubtitle(value As String) As String
            Return NormalizeText(value, MaxSubtitleLength)
        End Function

        Friend Shared Function NormalizeTrendText(value As String) As String
            Return NormalizeText(value, MaxTrendLength)
        End Function

        Friend Shared Function NormalizeText(value As String,
                                             maxLength As Integer) As String
            Dim s As String = If(value, String.Empty)
            s = s.Replace(vbCrLf, " ")
            s = s.Replace(vbCr, " ")
            s = s.Replace(vbLf, " ")
            Dim collapsed As String = CollapseSpaces(s).Trim()
            Dim safeMax As Integer = Math.Max(0, maxLength)
            If safeMax > 0 AndAlso collapsed.Length > safeMax Then Return collapsed.Substring(0, safeMax)
            Return collapsed
        End Function

        Private Shared Function CollapseSpaces(value As String) As String
            If String.IsNullOrEmpty(value) Then Return String.Empty
            Dim chars As New List(Of Char)(value.Length)
            Dim previousSpace As Boolean
            For Each ch As Char In value
                Dim isSpace As Boolean = Char.IsWhiteSpace(ch)
                If isSpace Then
                    If Not previousSpace Then chars.Add(" "c)
                Else
                    chars.Add(ch)
                End If
                previousSpace = isSpace
            Next
            Return New String(chars.ToArray())
        End Function

        Friend Shared Function NormalizeTone(value As MASToastTone) As MASToastTone
            Select Case value
                Case MASToastTone.Neutral, MASToastTone.Success, MASToastTone.Info, MASToastTone.Warning, MASToastTone.Danger
                    Return value
                Case Else
                    Return MASToastTone.Info
            End Select
        End Function

        Friend Shared Function NormalizeTrendVisible(showTrend As Boolean,
                                                     trendText As String) As Boolean
            Return showTrend AndAlso NormalizeTrendText(trendText).Length > 0
        End Function

        Friend Shared Function NormalizeSparklineSamples(samples As IEnumerable(Of Double)) As List(Of Double)
            Dim result As New List(Of Double)()
            If samples Is Nothing Then Return result
            For Each sample As Double In samples
                If Double.IsNaN(sample) OrElse Double.IsInfinity(sample) Then Continue For
                result.Add(sample)
                If result.Count >= MaxSparklineSamples Then Exit For
            Next
            Return result
        End Function

        Friend Shared Function BuildFormattedValue(value As Double,
                                                   Optional suffix As String = Nothing) As String
            If Double.IsNaN(value) OrElse Double.IsInfinity(value) Then value = 0.0R
            Dim absValue As Double = Math.Abs(value)
            Dim format As String
            If absValue >= 1000.0R Then
                format = "N0"
            ElseIf Math.Abs(value - Math.Truncate(value)) < 0.001R Then
                format = "0"
            Else
                format = "0.##"
            End If
            Return value.ToString(format, CultureInfo.CurrentCulture) & NormalizeSuffix(suffix)
        End Function

        Friend Shared Function NormalizeSuffix(value As String) As String
            Dim text As String = NormalizeText(value, 12)
            If text.Length = 0 Then Return String.Empty
            Return " " & text
        End Function

        Friend Shared Function ResolveRightToLeft() As Boolean
            Try
                Return Nexamas.UI.Localization.MASLocalization.IsCurrentRightToLeft()
            Catch ex As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowInputBoundary(ex, "MASMetricCardPolicy.ResolveRightToLeft")
                Return False
            End Try
        End Function

        Friend Shared Function ResolveToneColor(ctx As MASThemeContext,
                                                tone As MASToastTone) As SKColor
            Dim normalized As MASToastTone = NormalizeTone(tone)
            If ctx IsNot Nothing AndAlso ctx.SemanticTheme IsNot Nothing Then
                Select Case normalized
                    Case MASToastTone.Success
                        Return ctx.SemanticTheme.Success
                    Case MASToastTone.Warning
                        Return ctx.SemanticTheme.Warning
                    Case MASToastTone.Danger
                        Return ctx.SemanticTheme.Danger
                    Case MASToastTone.Info
                        Return ctx.SemanticTheme.Info
                End Select
            End If
            If normalized = MASToastTone.Neutral AndAlso ctx IsNot Nothing AndAlso ctx.BrandTheme IsNot Nothing Then Return ctx.BrandTheme.BrandPrimary
            If ctx IsNot Nothing AndAlso ctx.BrandTheme IsNot Nothing Then Return ctx.BrandTheme.BrandPrimary
            Return New SKColor(64, 132, 246)
        End Function

        Friend Shared Function ResolveTitleColor(ctx As MASThemeContext) As SKColor
            If ctx IsNot Nothing AndAlso ctx.TextColorTheme IsNot Nothing Then Return ctx.TextColorTheme.SecondaryText.WithAlpha(MetricCardTokens.TitleTextAlpha)
            Return Nexamas.UI.Values.Color.Text.Secondary.WithAlpha(MetricCardTokens.TitleTextAlpha)
        End Function

        Friend Shared Function ResolveValueColor(ctx As MASThemeContext) As SKColor
            If ctx IsNot Nothing AndAlso ctx.TextColorTheme IsNot Nothing Then Return ctx.TextColorTheme.PrimaryText.WithAlpha(MetricCardTokens.ValueTextAlpha)
            Return Nexamas.UI.Values.Color.Text.Primary.WithAlpha(MetricCardTokens.ValueTextAlpha)
        End Function

        Friend Shared Function ResolveSubtitleColor(ctx As MASThemeContext) As SKColor
            If ctx IsNot Nothing AndAlso ctx.TextColorTheme IsNot Nothing Then Return ctx.TextColorTheme.SecondaryText.WithAlpha(MetricCardTokens.SubtitleTextAlpha)
            Return Nexamas.UI.Values.Color.Text.Secondary.WithAlpha(MetricCardTokens.SubtitleTextAlpha)
        End Function

        Friend Shared Function HasNoMetricStoragePath() As Boolean
            Return True
        End Function

        Friend Shared Function HasNoAnalyticsCollectionPath() As Boolean
            Return True
        End Function

        Friend Shared Function HasNoTelemetryRefreshLoop() As Boolean
            Return True
        End Function

        Friend Shared Function HasNoChartEnginePath() As Boolean
            Return True
        End Function

        Friend Shared Function HasNoDashboardCompositionPath() As Boolean
            Return True
        End Function
    End Class

End Namespace
