import { getCsrfToken } from '../../utils/helpers.js';

export function initRegisterModal($container) {
    $('body').append(`
        <div class="modal fade" id="register-modal" tabindex="-1" data-bs-backdrop="static">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header border-0 pb-0">
                        <h5 class="modal-title fw-bold">
                            <i class="bi bi-person-plus me-2" style="color:var(--tennis-green)"></i>Регистрация
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body pt-2">
                        <p class="text-muted small mb-3">
                            Введите вашу почту — мы пришлём пароль для входа.
                        </p>

                        <div id="register-success" class="alert alert-success d-none">
                            <i class="bi bi-check-circle me-2"></i>
                            <span id="register-success-text"></span>
                        </div>
                        <div id="register-error" class="alert alert-danger d-none">
                            <i class="bi bi-exclamation-triangle me-2"></i>
                            <span id="register-error-text"></span>
                        </div>

                        <div id="register-form-body">
                            <div class="form-floating">
                                <input type="email" class="form-control" id="reg-email"
                                       placeholder="email@example.com" autocomplete="email">
                                <label for="reg-email" class="ms-2">
                                    <i class="bi bi-envelope me-1"></i>Email
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer border-0 pt-0" id="register-modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
                        <button type="button" class="btn fw-bold" id="register-submit-btn"
                                style="background:var(--tennis-green);color:#fff;border-radius:20px;padding:8px 22px;">
                            <i class="bi bi-send me-1"></i>Отправить
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `);

    // ── Сброс состояния при открытии ──
    $('#register-modal').on('show.bs.modal', () => {
        $('#reg-email').val('').removeClass('is-invalid');
        $('#register-success,#register-error').addClass('d-none');
        $('#register-form-body,#register-modal-footer').show();
    });

    // ── Отправка ──
    $('body').on('click', '#register-submit-btn', function () {
        const email = $('#reg-email').val().trim();

        if (!email || !email.includes('@')) {
            $('#reg-email').addClass('is-invalid');
            return;
        }
        $('#reg-email').removeClass('is-invalid');

        const $btn  = $(this);
        const orig  = $btn.html();
        $btn.html('<span class="spinner-border spinner-border-sm"></span>').prop('disabled', true);

        $.ajax({
            url: '/api/auth/register',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ email }),
            beforeSend: xhr => xhr.setRequestHeader('X-XSRF-TOKEN', getCsrfToken()),
            success: (resp) => {
                $('#register-error').addClass('d-none');
                $('#register-success-text').text(resp.message);
                $('#register-success').removeClass('d-none');
                // Скрываем форму и кнопки — только сообщение об успехе
                $('#register-form-body').hide();
                $('#register-modal-footer').hide();
            },
            error: (xhr) => {
                const msg = xhr.responseJSON?.message || 'Произошла ошибка. Попробуйте позже.';
                $('#register-error-text').text(msg);
                $('#register-error').removeClass('d-none');
            },
            complete: () => $btn.html(orig).prop('disabled', false)
        });
    });
}
