@using Common.Validation
@using HushianWebApp.Service
@inject AuthService AuthService
@inject VerificationService verificationService;
<div class="login-form">
    <div class="text-center mb-4">
        <span class="badge bg-info p-2 rounded-pill">نیاز برای ارتباط با کارشناسان وارد شود</span>
    </div>
    <div class="form-container">
        <Spinner Class="me-3" Type="SpinnerType.Dots" Color="SpinnerColor.Primary" Visible="@visible" />

        @if (ID == 0)
        {

            <label for="user-name" class="block mb-2 text-slate-600 font-bold">
                شماره همراه / نام کاربری
            </label>
            <div class="d-flex">

                <div class="container-input" style="width:150px;margin-left:5px">
                    <input type="text"
                    id="user-name"
                    maxlength="13"
                    style="text-align:center;height:30px;@validateStyleUser"
                    title="شماره همراه را وارد کنید. مثل 0911-966-0045"
                    class="input-form input_vk_1"
                    required
                    data-val="true"
                    data-val-required="شماره همراه را وارد کنید."
                    name="Username"
                    oninput="formatPhoneNumber(this)"
                    @bind-value=Username>
                </div>
                <Button disabled="visible" Color="ButtonColor.Primary" Type="ButtonType.Submit" @onclick="Login" class="btn-primary"
                style="text-align:center;height:30px">
                    ورود
                </Button>
            </div>
        }
        else
        {
            <label for="user-name" class="block mb-2 text-slate-600 font-bold">
                جهت احراز کد ارسال شده را وارد کنید
            </label>

            <div class="d-flex justify-content-center">

                <div class="verification-inputs" style="display: flex; gap: 8px; direction: ltr;">
                    <input maxlength="1" type="text" inputmode="numeric" pattern="[0-9]*"
                    @bind="code1" @oninput="MoveNext"
                    style="width: 45px; height: 45px; text-align: center; border: 2px solid #ccc; border-radius: 8px; font-size: 18px; font-weight: bold;"
                    @ref="input1" autoFocus />

                    <input maxlength="1" type="text" inputmode="numeric" pattern="[0-9]*"
                    @bind="code2" @oninput="MoveNext"
                    style="width: 45px; height: 45px; text-align: center; border: 2px solid #ccc; border-radius: 8px; font-size: 18px; font-weight: bold;"
                    @ref="input2" />

                    <input maxlength="1" type="text" inputmode="numeric" pattern="[0-9]*"
                    @bind="code3" @oninput="MoveNext"
                    style="width: 45px; height: 45px; text-align: center; border: 2px solid #ccc; border-radius: 8px; font-size: 18px; font-weight: bold;"
                    @ref="input3" />

                    <input maxlength="1" type="text" inputmode="numeric" pattern="[0-9]*"
                    @bind="code4" @oninput="OnLastInput"
                    style="width: 45px; height: 45px; text-align: center; border: 2px solid #ccc; border-radius: 8px; font-size: 18px; font-weight: bold;"
                    @ref="input4" />

                </div>

            </div>
            <Button Color="ButtonColor.Link"
                    Disabled="@isButtonDisabled"
                    @onclick="async () =>
        {
            await verificationService.ReSendCode(ID);
            await verifiTimer();
        }"
                    Style="padding: 6px 16px; font-size: 14px;  background-color: #f8f9fa; transition: all 0.3s ease; display: inline-flex; align-items: center; gap: 8px;    margin-top: 10px;margin-bottom: -10px;">

                <span>ارسال مجدد</span>

                @if (countdown > 0)
                {
                    <span style="color: #dc3545; font-weight: bold;">(@countdown)</span>
                }
            </Button>



        }
    </div>
</div>


@code {
    private bool visible = false;
    [Parameter] public EventCallback OnMultipleOfThree { get; set; }
    public string Username { get; set; }
    public int ID { get; set; } = 0;
    public string Code { get; set; } = string.Empty;
    //-----------------
    private string code1, code2, code3, code4;
    private ElementReference input1, input2, input3, input4;
    string validateStyleUser = "";
    private bool isButtonDisabled = true;
    private int countdown = 60;
    private System.Timers.Timer? timer;
}
@functions {
    async Task Login()
    {
        if (Username.Replace("-", "").CheckMobile())
        {
            visible = true;
            ID = await AuthService.login(new Common.Models.Auth.UserSide.AuthRequestFromUserSide()
                {
                    Mobile = Username.Replace("-", "")
                });
            validateStyleUser = "";
            await verifiTimer();
            visible = false;
        }
        else
        {
            validateStyleUser = " border: 2px solid red; border-radius: 4px;";
        }

    }
    async Task verifiTimer()
    {
        //----------
        isButtonDisabled = true;
        countdown = 60;
        timer = new System.Timers.Timer(1000); // هر 1 ثانیه
        timer.Elapsed += OnTimerElapsed;
        timer.AutoReset = true;
        timer.Enabled = true;
        //----------
    }
    private void OnTimerElapsed(object? sender, System.Timers.ElapsedEventArgs e)
    {
        if (countdown > 0)
        {
            countdown--;
            InvokeAsync(StateHasChanged); // بروزرسانی UI
        }

        if (countdown == 0)
        {
            isButtonDisabled = false;
            timer?.Stop();
            timer?.Dispose();
            StateHasChanged();
        }
    }
    async Task ver()
    {
        visible = true;
        if (await AuthService.Verificationlogin(ID, Code))
            await OnMultipleOfThree.InvokeAsync();
        visible = false;
    }
    private async Task MoveNext(ChangeEventArgs e)
    {
        if (e.Value?.ToString()?.Length == 1)
        {
            if (input1.Context == null) return;

            if (string.IsNullOrEmpty(code1))
                await input2.FocusAsync();
            else if (string.IsNullOrEmpty(code2))
                await input3.FocusAsync();
            else if (string.IsNullOrEmpty(code3))
                await input4.FocusAsync();
            else if (string.IsNullOrEmpty(code4))
            {
                Code = $"{code1}{code2}{code3}{code4}";
            }
        }
    }
    private async Task OnLastInput(ChangeEventArgs e)
    {
        code4 = e.Value?.ToString();

        if (!string.IsNullOrEmpty(code4) && code4.Length == 1)
        {
            Code = $"{code1}{code2}{code3}{code4}";

            await ver();
        }
    }
}
<script>
    function formatPhoneNumber(input) {
      let value = input.value.replace(/\D/g, ''); // فقط عدد
      if (value.length > 11) value = value.slice(0, 11); // حداکثر 11 رقم

      let formatted = '';
      if (value.length >= 4) {
        formatted += value.slice(0, 4) + '-';
        if (value.length >= 7) {
          formatted += value.slice(4, 7) + '-';
          formatted += value.slice(7);
        } else {
          formatted += value.slice(4);
        }
      } else {
        formatted = value;
      }

      input.value = formatted;
    }
</script>
<style>
    .login-form {
        width: 100%;
    }

    .form-container {
        width: 100%;
    }

        .form-container label {
            display: block;
            margin-bottom: 0.75rem;
            font-weight: 600;
            color: #495057;
        }

        .form-container .d-flex {
            gap: 0.75rem;
            align-items: center;
        }

    .container-input {
        flex: 1;
    }

        .container-input input {
            width: 100%;
            border: 2px solid #e9ecef;
            border-radius: 0.5rem;
            transition: border-color 0.2s ease;
        }

            .container-input input:focus {
                border-color: #0d6efd;
                outline: none;
                box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
            }

    .form-container input[type="text"] {
        margin: 0 0.25rem;
        transition: all 0.2s ease;
    }

        .form-container input[type="text"]:focus {
            border-color: #0d6efd;
            box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
        }

    .badge {
        font-size: 0.875rem;
        font-weight: 500;
    }

    .verification-inputs {
        flex-wrap: nowrap;
        justify-content: center;
        align-items: center;
    }

        .verification-inputs input {
            flex-shrink: 0;
            transition: all 0.2s ease;
        }

            .verification-inputs input:focus {
                border-color: #0d6efd;
                box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
                transform: scale(1.05);
            }
</style>