@namespace SufiChain.SufiBlazor.Components.Forms
@typeparam TValue

<label class="@CssClass" style="@Style">
    <span class="sb-radio__input-wrapper">
        <input type="radio"
               class="sb-radio__input"
               id="@Id"
               name="@RadioGroup?.GroupName"
               value="@Value"
               checked="@IsChecked"
               disabled="@IsDisabled"
               @onchange="HandleChange"
               @attributes="InputAttributes" />
    </span>
    <span class="sb-radio__circle">
        <span class="sb-radio__dot"></span>
    </span>
    <span class="sb-radio__text">
        @if (!string.IsNullOrEmpty(Label) || ChildContent != null)
        {
            <span class="sb-radio__label">
                @if (ChildContent != null)
                {
                    @ChildContent
                }
                else
                {
                    @Label
                }
            </span>
        }
        @if (!string.IsNullOrEmpty(EffectiveHelperText))
        {
            <span class="sb-radio__helper">@EffectiveHelperText</span>
        }
    </span>
</label>

@code {
    /// <summary>
    /// Radio value.
    /// </summary>
    [Parameter]
    public TValue? Value { get; set; }

    /// <summary>
    /// Radio label.
    /// </summary>
    [Parameter]
    public string? Label { get; set; }

    /// <summary>
    /// Whether this radio is disabled.
    /// </summary>
    [Parameter]
    public bool Disabled { get; set; }

    /// <summary>
    /// Optional helper text shown below the label (e.g. "Basic features").
    /// </summary>
    [Parameter]
    public string? HelperText { get; set; }

    /// <summary>
    /// Custom label content.
    /// </summary>
    [Parameter]
    public RenderFragment? ChildContent { get; set; }

    /// <summary>
    /// Element ID for the input.
    /// </summary>
    [Parameter]
    public string? Id { get; set; }

    /// <summary>
    /// Additional CSS classes.
    /// </summary>
    [Parameter]
    public string? Class { get; set; }

    /// <summary>
    /// Inline styles.
    /// </summary>
    [Parameter]
    public string? Style { get; set; }

    /// <summary>
    /// Additional HTML attributes.
    /// </summary>
    [Parameter(CaptureUnmatchedValues = true)]
    public Dictionary<string, object>? AdditionalAttributes { get; set; }

    [CascadingParameter]
    private SbRadioGroup<TValue>? RadioGroup { get; set; }

    /// <summary>Helper text from parameter or from AdditionalAttributes (so it never gets splatted onto the input).</summary>
    private string? EffectiveHelperText => !string.IsNullOrEmpty(HelperText)
        ? HelperText
        : GetAdditionalAttribute("helpertext") ?? GetAdditionalAttribute("HelperText");

    /// <summary>Attributes for the input, excluding HelperText so it is not rendered on the input element.</summary>
    private IReadOnlyDictionary<string, object>? InputAttributes
    {
        get
        {
            if (AdditionalAttributes == null || AdditionalAttributes.Count == 0)
                return null;
            var filtered = new Dictionary<string, object>(AdditionalAttributes);
            filtered.Remove("helpertext");
            filtered.Remove("HelperText");
            return filtered;
        }
    }

    private string? GetAdditionalAttribute(string key)
    {
        if (AdditionalAttributes == null) return null;
        if (AdditionalAttributes.TryGetValue(key, out var value) && value is string s)
            return s;
        var keyLower = key.ToLowerInvariant();
        foreach (var kv in AdditionalAttributes)
        {
            if (string.Equals(kv.Key, key, StringComparison.OrdinalIgnoreCase) && kv.Value is string s2)
                return s2;
        }
        return null;
    }

    private bool IsChecked => RadioGroup?.IsSelected(Value) ?? false;
    private bool IsDisabled => Disabled || (RadioGroup?.Disabled ?? false);

    private string CssClass
    {
        get
        {
            var classes = new List<string> { "sb-radio" };

            if (IsChecked)
            {
                classes.Add("sb-radio--checked");
            }

            if (IsDisabled)
            {
                classes.Add("sb-radio--disabled");
            }

            if (!string.IsNullOrWhiteSpace(Class))
            {
                classes.Add(Class);
            }

            return string.Join(" ", classes);
        }
    }

    private async Task HandleChange(ChangeEventArgs e)
    {
        if (RadioGroup != null && Value != null)
        {
            await RadioGroup.SelectValue(Value);
        }
    }
}
