@namespace SufiChain.SufiBlazor.Components.Forms

<div class="@CssClass" style="@Style" @attributes="AdditionalAttributes">
    @if (!string.IsNullOrEmpty(Label))
    {
        <label class="sb-form-field__label" for="@InputId">
            @Label
            @if (Required)
            {
                <span class="sb-form-field__required" aria-hidden="true">*</span>
            }
        </label>
    }

    <div class="sb-form-field__input">
        @ChildContent
    </div>

    @if (!string.IsNullOrEmpty(HelperText) && string.IsNullOrEmpty(ErrorText))
    {
        <div class="sb-form-field__helper" id="@HelperId">@HelperText</div>
    }

    @if (!string.IsNullOrEmpty(ErrorText))
    {
        <div class="sb-form-field__error" id="@ErrorId" role="alert">@ErrorText</div>
    }
</div>

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

    /// <summary>
    /// Helper text shown below the input.
    /// </summary>
    [Parameter]
    public string? HelperText { get; set; }

    /// <summary>
    /// Error text shown below the input.
    /// </summary>
    [Parameter]
    public string? ErrorText { get; set; }

    /// <summary>
    /// Whether the field is required.
    /// </summary>
    [Parameter]
    public bool Required { get; set; }

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

    /// <summary>
    /// ID for the input element (used for label association).
    /// </summary>
    [Parameter]
    public string? InputId { get; set; }

    /// <summary>
    /// Field content (input element).
    /// </summary>
    [Parameter]
    public RenderFragment? ChildContent { 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; }

    private string HelperId => $"{InputId}-helper";
    private string ErrorId => $"{InputId}-error";

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

            if (!string.IsNullOrEmpty(ErrorText))
            {
                classes.Add("sb-form-field--error");
            }

            if (Disabled)
            {
                classes.Add("sb-form-field--disabled");
            }

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

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