<Rows>
    <Markup Content="@Loc.SettingsTitle" Foreground="@UiPalette.Text" Decoration="@Spectre.Console.Decoration.Bold" />
    <Markup Content=" " />

    @if (Entries.Count == 0)
    {
        <Border BorderColor="@UiPalette.Frame" BoxBorder="@Spectre.Console.BoxBorder.Rounded" Padding="@(new Spectre.Console.Padding(0, 0, 0, 0))">
            <Markup Content="@Loc.SettingsEmpty" Foreground="@UiPalette.TextDim" />
        </Border>
    }
    else
    {
        <Select TItem="int"
                Options="@GetOptions()"
                Value="@GetNormalizedIndex()"
                FocusedValue="@GetNormalizedIndex()"
                Formatter="@FormatEntry"
                Expand="true"
                BorderStyle="@Spectre.Console.BoxBorder.Rounded"
                SelectedIndicator="@('>')" />
    }

    <Markup Content=" " />
    <Markup Content="@GetSelectedDescription()" Foreground="@UiPalette.TextMuted" />
</Rows>

@code {
    [Parameter, EditorRequired] public IReadOnlyList<SettingsEntry> Entries { get; set; } = Array.Empty<SettingsEntry>();
    [Parameter] public int SelectedIndex { get; set; }
    [Parameter] public EventCallback<int> SelectedIndexChanged { get; set; }
    [Parameter] public int ViewportRows { get; set; } = 5;
    [Parameter] public TuiResources Loc { get; set; } = TuiResources.En;

    private int[] GetOptions() => Enumerable.Range(0, Entries.Count).ToArray();

    private int GetNormalizedIndex() => Entries.Count == 0 ? 0 : Math.Clamp(SelectedIndex, 0, Entries.Count - 1);

    private string GetSelectedDescription()
    {
        if (Entries.Count == 0)
        {
            return Loc.SettingsUnavailable;
        }

        var selected = Entries[Math.Clamp(SelectedIndex, 0, Entries.Count - 1)];
        return selected.Description;
    }

    private string FormatEntry(int index)
    {
        var entry = Entries[index];
        var indent = new string(' ', entry.Depth * 4);
        var checkbox = entry.IsChecked ? "[x]" : "[ ]";
        var disabledSuffix = entry.Kind == SettingsEntryKind.Tool && !entry.IsModuleEnabled
            ? $" {Loc.ModuleOff}"
            : string.Empty;

        string text;
        if (entry.Kind == SettingsEntryKind.Module)
        {
            var expander = entry.IsExpanded ? "[-]" : "[+]";
            text = $"{expander} {checkbox} {entry.Label}";
        }
        else
        {
            text = $"{indent}{checkbox} {entry.Label}{disabledSuffix}";
        }

        return Fit(text, Math.Max(UiMetrics.ConsoleWidth - 12, 32));
    }

    private static string Fit(string text, int width)
    {
        if (width <= 0) return string.Empty;
        if (text.Length <= width) return text.PadRight(width);
        if (width <= 3) return text[..width];
        return text[..(width - 3)] + "...";
    }
}
