@using Common.Dtos.Conversation
@using HushianWebApp.Service
@inject IJSRuntime JSRuntime
@inject ConversationService conversationService;

<div class="chat-container p-3">

    @foreach (var msg in Messages)
    {
        @if (!target && ((!msg.IsRead && msg.Type == Common.Enums.ConversationType.UE) || Messages.Last() == msg))
        {
            target = true;
            <div id="target" style="text-align: center;">
                @if (!msg.IsRead && msg.Type == Common.Enums.ConversationType.UE)
                {
                    <p>ـــــــــــــــــــــــــ</p>
                }

            </div>
        }



        <div class="d-flex mb-2 @(msg.Type==Common.Enums.ConversationType.UE ? "justify-content-end" : "justify-content-start")">
            <div class="chat-bubble @(msg.Type==Common.Enums.ConversationType.UE ? "chat-mine"
           : "chat-other")" data-id="@msg.ID">
                @msg.text
            </div>
            @if (msg.Type == Common.Enums.ConversationType.EU)
            {
                if (msg.IsRead)
                {
                    <Icon Style="align-self: self-end;" Name="IconName.CheckAll" Size="IconSize.x5" Color="IconColor.Success" />

                }
                else
                {
                    <Icon Style="align-self: self-end;" Name="IconName.CheckLg" Size="IconSize.x5" />

                }
            }


        </div>

    }
</div>

<style>
    .chat-bubble {
        padding: 0.5rem 0.75rem;
        border-radius: 1rem;
        max-width: 75%;
        word-wrap: break-word;
        white-space: pre-wrap;
    }

    .chat-mine {
        background: linear-gradient(to right, #005eff, #267fff);
        color: white;
        border-top-left-radius: 0;
    }

    .chat-other {
        background-color: #f1f1f1;
        color: #333;
        border-top-right-radius: 0;
    }

    .chat-ai {
        background-color: #f1f1f1;
        color: #353;
        border-top-right-radius: 0;
    }
</style>

@code {
    bool target = false;
    [Parameter]
    public List<Read_ConversationResponseDto> Messages { get; set; } = new();
    [Parameter] public EventCallback<int> EventCallIsRead { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JSRuntime.InvokeVoidAsync("observeVisibility", DotNetObjectReference.Create(this));
            await JSRuntime.InvokeVoidAsync("scrollToTarget");

        }
    }
    [JSInvokable]
    public async Task MarkAsRead(int id)
    {
        var msg = Messages.FirstOrDefault(m => m.ID == id);
        if (msg != null && !msg.IsRead && msg.Type == Common.Enums.ConversationType.UE)
        {
            msg.IsRead = true;
            await conversationService.MarkAsReadConversationItemAsync(id);

            // await EventCallIsRead.InvokeAsync(id);
        }
        await Task.CompletedTask;
    }
}
