<header class="table-browser-header tables-context-bar">
    <div class="tables-context-primary">
        <div>
            <h2 class="panel-title">@Detail.DisplayName</h2>
            <p class="table-browser-reading-hint">@GetReadingHint()</p>
        </div>
        <div class="action-row">
            <button type="button" class="btn btn-link" @onclick="() => OnTogglePin.InvokeAsync()">
                @(IsPinned ? "Unpin table" : "Pin table")
            </button>
            <p class="table-browser-edit-hint">Use the inspector to inspect, curate, or edit the selected result.</p>
        </div>
    </div>

    <div class="tables-context-controls">
        <div class="tables-context-tab-row">
            <SegmentedTabs
                Items="modeTabs"
                SelectedValue="CurrentMode"
                SelectedValueChanged="OnModeChanged"
                AriaLabel="Reference mode"
                CssClass="tables-context-mode-tabs" />

            <SegmentedTabs
                Items="densityTabs"
                SelectedValue="DensityMode"
                SelectedValueChanged="OnDensityChanged"
                AriaLabel="Table density"
                CssClass="tables-context-density-tabs" />
        </div>

        <div class="tables-context-fields">
            @if (Detail.Groups.Count > 1)
            {
                <label class="tables-context-field">
                    <span>Variant</span>
                    <select class="input-shell" value="@SelectedGroupKey" @onchange="HandleGroupChanged">
                        <option value="">All variants</option>
                        @foreach (var group in Detail.Groups)
                        {
                            <option value="@group.Key">@group.Label</option>
                        }
                    </select>
                </label>
            }

            @if (Detail.Columns.Count > 1)
            {
                <label class="tables-context-field">
                    <span>Severity focus</span>
                    <select class="input-shell" value="@SelectedColumnKey" @onchange="HandleColumnChanged">
                        <option value="">All severities</option>
                        @foreach (var column in Detail.Columns)
                        {
                            <option value="@column.Key">@column.Label</option>
                        }
                    </select>
                </label>
            }

            <label class="tables-context-field">
                <span>Roll jump</span>
                <input
                    class="input-shell"
                    inputmode="numeric"
                    pattern="[0-9]*"
                    placeholder="e.g. 66"
                    value="@RollJumpValue"
                    @oninput="HandleRollJumpChanged" />
            </label>
        </div>

        @if (HasActiveFilters())
        {
            <div class="tables-context-filter-chips" aria-label="Active table filters">
                @if (!string.IsNullOrWhiteSpace(SelectedGroupLabel))
                {
                    <button type="button" class="tables-context-filter-chip" @onclick="() => OnGroupChanged.InvokeAsync(string.Empty)">
                        Variant: @SelectedGroupLabel
                    </button>
                }

                @if (!string.IsNullOrWhiteSpace(SelectedColumnLabel))
                {
                    <button type="button" class="tables-context-filter-chip" @onclick="() => OnColumnChanged.InvokeAsync(string.Empty)">
                        Severity: @SelectedColumnLabel
                    </button>
                }

                @if (!string.IsNullOrWhiteSpace(RollJumpValue))
                {
                    <button type="button" class="tables-context-filter-chip" @onclick="() => OnRollJumpChanged.InvokeAsync(string.Empty)">
                        Roll: @RollJumpValue
                    </button>
                }

                @if (!string.Equals(CurrentMode, TablesReferenceMode.Reference, StringComparison.Ordinal))
                {
                    <button type="button" class="tables-context-filter-chip" @onclick="() => OnModeChanged.InvokeAsync(TablesReferenceMode.Reference)">
                        Mode: @GetModeLabel(CurrentMode)
                    </button>
                }
            </div>
        }
    </div>
</header>

@code {
    private readonly IReadOnlyList<SegmentedTabItem> modeTabs =
    [
        new(TablesReferenceMode.Reference, "Reference"),
        new(TablesReferenceMode.NeedsCuration, "Needs Curation"),
        new(TablesReferenceMode.Curated, "Curated")
    ];

    private readonly IReadOnlyList<SegmentedTabItem> densityTabs =
    [
        new(TablesDensityMode.Comfortable, "Comfortable"),
        new(TablesDensityMode.Dense, "Dense")
    ];

    [Parameter, EditorRequired]
    public CriticalTableDetail Detail { get; set; } = default!;

    [Parameter]
    public bool IsPinned { get; set; }

    [Parameter]
    public string CurrentMode { get; set; } = TablesReferenceMode.Reference;

    [Parameter]
    public string SelectedGroupKey { get; set; } = string.Empty;

    [Parameter]
    public string SelectedColumnKey { get; set; } = string.Empty;

    [Parameter]
    public string RollJumpValue { get; set; } = string.Empty;

    [Parameter]
    public string DensityMode { get; set; } = TablesDensityMode.Comfortable;

    [Parameter]
    public EventCallback OnTogglePin { get; set; }

    [Parameter]
    public EventCallback<string> OnModeChanged { get; set; }

    [Parameter]
    public EventCallback<string> OnGroupChanged { get; set; }

    [Parameter]
    public EventCallback<string> OnColumnChanged { get; set; }

    [Parameter]
    public EventCallback<string> OnRollJumpChanged { get; set; }

    [Parameter]
    public EventCallback<string> OnDensityChanged { get; set; }

    private string GetReadingHint() =>
        Detail.Groups.Count > 0
            ? "Find the roll band on the left, then read across to the group and severity you need."
            : "Find the roll band on the left, then read across to the severity you need.";

    private string? SelectedGroupLabel =>
        Detail.Groups.FirstOrDefault(group => string.Equals(group.Key, SelectedGroupKey, StringComparison.OrdinalIgnoreCase))?.Label;

    private string? SelectedColumnLabel =>
        Detail.Columns.FirstOrDefault(column => string.Equals(column.Key, SelectedColumnKey, StringComparison.OrdinalIgnoreCase))?.Label;

    private bool HasActiveFilters() =>
        !string.IsNullOrWhiteSpace(SelectedGroupKey)
        || !string.IsNullOrWhiteSpace(SelectedColumnKey)
        || !string.IsNullOrWhiteSpace(RollJumpValue)
        || !string.Equals(CurrentMode, TablesReferenceMode.Reference, StringComparison.Ordinal);

    private Task HandleGroupChanged(ChangeEventArgs args) =>
        OnGroupChanged.InvokeAsync(args.Value?.ToString() ?? string.Empty);

    private Task HandleColumnChanged(ChangeEventArgs args) =>
        OnColumnChanged.InvokeAsync(args.Value?.ToString() ?? string.Empty);

    private Task HandleRollJumpChanged(ChangeEventArgs args) =>
        OnRollJumpChanged.InvokeAsync(args.Value?.ToString() ?? string.Empty);

    private static string GetModeLabel(string mode) =>
        mode switch
        {
            TablesReferenceMode.NeedsCuration => "Needs Curation",
            TablesReferenceMode.Curated => "Curated",
            _ => "Reference"
        };
}
