@if (IsVisible)
{
    <div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h6 class="modal-title">Move '@TemplateName' to…</h6>
                    <button type="button" class="btn-close" @onclick="Close"></button>
                </div>
                <div class="modal-body">
                    <select class="form-select form-select-sm" @bind="_targetFolderId">
                        @foreach (var opt in FolderOptions)
                        {
                            <option value="@opt.Id">@opt.Label</option>
                        }
                    </select>
                    @if (!string.IsNullOrEmpty(ErrorMessage)) { <div class="text-danger small mt-1">@ErrorMessage</div> }
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline-secondary btn-sm" @onclick="Close">Cancel</button>
                    <button class="btn btn-primary btn-sm" @onclick="Submit">Move</button>
                </div>
            </div>
        </div>
    </div>
}

@code {
    [Parameter] public bool IsVisible { get; set; }
    [Parameter] public EventCallback<bool> IsVisibleChanged { get; set; }
    [Parameter] public int TemplateId { get; set; }
    [Parameter] public string TemplateName { get; set; } = string.Empty;
    [Parameter] public IEnumerable<(int? Id, string Label)> FolderOptions { get; set; } = Array.Empty<(int?, string)>();
    [Parameter] public string? ErrorMessage { get; set; }
    [Parameter] public EventCallback<(int TemplateId, int? NewFolderId)> OnSubmit { get; set; }

    private bool _wasVisible;
    private int? _targetFolderId;

    protected override void OnParametersSet()
    {
        // Reset internal state on transition from hidden -> visible.
        if (IsVisible && !_wasVisible)
        {
            _targetFolderId = null;
        }
        _wasVisible = IsVisible;
    }

    private async Task Close()
    {
        await IsVisibleChanged.InvokeAsync(false);
    }

    private async Task Submit()
    {
        await OnSubmit.InvokeAsync((TemplateId, _targetFolderId));
    }
}
