@page "/exercises"
@page "/{UserId}/exercises"

@inject ApiClient Api
@inject NavigationManager Navigation
@inject UserContext UserContext
@inject IJSRuntime JS

<PageTitle>Exercises</PageTitle>

<div class="page">
    <header class="page-header">
        <h1>Exercises</h1>
        <p>Create and manage your exercise list.</p>
        <button class="primary" @onclick="ToggleCreate">@(ShowCreateExercise ? "Close" : "+")</button>
    </header>

    @if (ShowCreateExercise)
    {
        <section class="card">
            <h2>Add Exercise</h2>
            <div class="form-row">
                <input class="input" placeholder="Exercise name" @bind="NewExerciseName" @bind:event="oninput" />
                <button class="primary" @onclick="CreateExerciseAsync" disabled="@string.IsNullOrWhiteSpace(NewExerciseName)">Add</button>
            </div>
        </section>
    }

    <section class="card">
        <h2>Your Exercises</h2>
        @if (IsLoading)
        {
            <p>Loading...</p>
        }
        else if (ExerciseList.Count == 0)
        {
            <p class="muted">No exercises yet. Add your first one above.</p>
        }
        else
        {
            <div class="list">
                @foreach (var exercise in ExerciseList)
                {
                    <div class="list-item" style="flex-direction: column; align-items: flex-start;">
                        @if (EditingId == exercise.Id)
                        {
                            <input class="input" @bind="EditingName" @bind:event="oninput" />
                            <div class="item-actions">
                                <button class="primary" @onclick="() => SaveEditAsync(exercise.Id)">Save</button>
                                <button class="ghost" @onclick="CancelEdit">Cancel</button>
                            </div>
                        }
                        else
                        {
                            <div class="item-title" style="text-overflow: ellipsis; white-space: nowrap; overflow: hidden; width: 100%;">@exercise.Name</div>
                            <div class="item-actions">
                                <button class="ghost" @onclick="() => StartEdit(exercise)" aria-label="Edit exercise">✏️</button>
                                <button class="ghost" @onclick="() => DeleteExerciseAsync(exercise.Id)" aria-label="Delete exercise">🗑️</button>
                            </div>
                        }
                    </div>
                }
            </div>
        }
    </section>
</div>

