@page "/einstellungen"
@inject IJSRuntime JS

<h3>Einstellungen</h3>

<div class="card" style="max-width:480px">
    <div class="card-body">
        <div class="mb-3">
            <label class="form-label">Filial-ID</label>
            <input class="form-control"
                   placeholder="z. B. 202"
                   @bind="filialId"
                   @onkeydown="HandleKeyDown"
                   autofocus />
            <div class="form-text">Wird lokal im Browser gespeichert.</div>
        </div>

        <div class="d-flex gap-2">
            <button class="btn btn-primary" @onclick="Save">Speichern</button>
            <button class="btn btn-outline-secondary" @onclick="Reload">Neu laden</button>
            <button class="btn btn-outline-danger" @onclick="Clear">Löschen</button>
        </div>

        @if (!string.IsNullOrEmpty(status))
        {
            <p class="mt-2" style="color:@(ok ? "green" : "crimson")">@status</p>
        }
    </div>
</div>

@code {
    private const string Key = "scannerpilot.filialId";
    private string? filialId;
    private string? status;
    private bool ok;

    protected override async Task OnInitializedAsync() => await Reload();

    private async Task Reload()
    {
        filialId = await JS.InvokeAsync<string?>("localStorage.getItem", Key);
        status = filialId is null ? "Noch keine Filial-ID hinterlegt." : $"Aktuelle Filial-ID: {filialId}";
        ok = filialId is not null;
        StateHasChanged();
    }

    private async Task Save()
    {
        if (string.IsNullOrWhiteSpace(filialId))
        {
            ok = false; status = "Bitte eine Filial-ID eingeben.";
            return;
        }

        await JS.InvokeVoidAsync("localStorage.setItem", Key, filialId.Trim());
        ok = true; status = $"Gespeichert: {filialId.Trim()}";
    }

    private async Task Clear()
    {
        await JS.InvokeVoidAsync("localStorage.removeItem", Key);
        filialId = null;
        ok = true; status = "Filial-ID entfernt.";
    }

    private async Task HandleKeyDown(KeyboardEventArgs e)
    {
        if (e.Key == "Enter") await Save();
    }
}
