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

let currentEvent = null;
let turnstileWidgetId = null;
let turnstileToken = null;

export function initApplyModal() {
    if (!$('#apply-event-modal').length) {
        $('body').append(buildApplyModal());
        setupApplyModal();
    }
}

export function openApplyModal(event) {
    currentEvent = event;
    $('#apply-event-name').text(event.title);
    clearApplyForm();
    bootstrap.Modal.getOrCreateInstance(document.getElementById('apply-event-modal')).show();
}

function buildApplyModal() {
    return `
    <div class="modal fade" id="apply-event-modal" tabindex="-1" data-bs-backdrop="static">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content border-0 rounded-4 overflow-hidden" style="box-shadow:0 20px 60px rgba(0,0,0,0.18)">

                <div style="background:linear-gradient(135deg,#2ecc71,#27ae60);padding:20px 24px;display:flex;align-items:center;justify-content:space-between">
                    <div class="d-flex align-items-center gap-2">
                        <div style="width:38px;height:38px;border-radius:9px;background:rgba(255,255,255,0.2);display:flex;align-items:center;justify-content:center;font-size:1.1rem;color:#fff">
                            <i class="bi bi-send"></i>
                        </div>
                        <div>
                            <h5 class="modal-title mb-0 text-white fw-bold">Подать заявку</h5>
                            <p class="mb-0 text-white opacity-75 small" id="apply-event-name"></p>
                        </div>
                    </div>
                    <button type="button" class="btn-close btn-close-white opacity-75" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body p-4" style="max-height:75vh;overflow-y:auto">

                    <p class="modal-section-label">Личные данные</p>
                    <div class="row g-3 mb-3">
                        <div class="col-12">
                            <div class="form-floating">
                                <input type="text" class="form-control rounded-3" id="apply-fullname" placeholder=" " required>
                                <label for="apply-fullname">ФИО <span class="text-danger">*</span></label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="email" class="form-control rounded-3" id="apply-email" placeholder=" " required>
                                <label for="apply-email">Email <span class="text-danger">*</span></label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="tel" class="form-control rounded-3" id="apply-phone" placeholder=" ">
                                <label for="apply-phone">Номер телефона</label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="date" class="form-control rounded-3" id="apply-birthdate" placeholder=" ">
                                <label for="apply-birthdate">Дата рождения</label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-floating">
                                <select class="form-select rounded-3" id="apply-gender">
                                    <option value="">— Не указывать —</option>
                                    <option value="Мужской">Мужской</option>
                                    <option value="Женский">Женский</option>
                                </select>
                                <label for="apply-gender">Пол</label>
                            </div>
                        </div>
                    </div>

                    <p class="modal-section-label">Спортивные данные</p>
                    <div class="row g-3 mb-3">
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="number" class="form-control rounded-3" id="apply-rating"
                                       placeholder=" " min="0" step="1">
                                <label for="apply-rating">Рейтинговые очки</label>
                            </div>
                        </div>
                    </div>

                    <p class="modal-section-label">Подтверждение</p>
                    <div id="apply-turnstile-container" class="mb-3"></div>

                    <div id="apply-alert" class="alert d-none mb-0"></div>
                </div>

                <div class="modal-footer border-0 px-4 pb-4 pt-2 gap-2">
                    <button type="button" class="btn btn-light fw-semibold px-4 rounded-3"
                            data-bs-dismiss="modal">Отмена</button>
                    <button type="button" class="btn fw-semibold px-4 rounded-3" id="apply-submit-btn"
                            style="background:var(--tennis-green);color:#fff;border:none">
                        <i class="bi bi-send me-1"></i>Отправить заявку
                    </button>
                </div>
            </div>
        </div>
    </div>`;
}

function setupApplyModal() {
    $('#apply-event-modal').on('shown.bs.modal', () => {
        renderTurnstile();
    });

    $('#apply-event-modal').on('hidden.bs.modal', () => {
        if (window.turnstile && turnstileWidgetId !== null) {
            window.turnstile.remove(turnstileWidgetId);
            turnstileWidgetId = null;
        }
        turnstileToken = null;
    });

    $('#apply-submit-btn').on('click', submitApplication);
}

function renderTurnstile() {
    const $container = $('#apply-turnstile-container').empty();
    turnstileToken = null;

    if (window.turnstile && window.turnstileSiteKey) {
        const el = $('<div></div>').appendTo($container)[0];
        turnstileWidgetId = window.turnstile.render(el, {
            sitekey: window.turnstileSiteKey,
            callback: token => { turnstileToken = token; }
        });
    } else {
        $container.html('<p class="text-muted small">Капча загружается...</p>');
    }
}

function clearApplyForm() {
    $('#apply-fullname,#apply-email,#apply-phone,#apply-birthdate').val('');
    $('#apply-gender').val('');
    $('#apply-rating').val('');
    $('#apply-alert').addClass('d-none').text('');
}

function showAlert(type, msg) {
    $('#apply-alert')
        .removeClass('d-none alert-success alert-danger')
        .addClass('alert-' + type)
        .text(msg);
}

function submitApplication() {
    const fullName = $('#apply-fullname').val().trim();
    const email    = $('#apply-email').val().trim();

    if (!fullName) { showAlert('danger', 'Введите ФИО'); return; }
    if (!email)    { showAlert('danger', 'Введите email'); return; }
    if (!turnstileToken) { showAlert('danger', 'Пройдите проверку капчи'); return; }

    const $btn = $('#apply-submit-btn');
    const orig = $btn.html();
    $btn.html('<span class="spinner-border spinner-border-sm me-1"></span>Отправка...').prop('disabled', true);
    $('#apply-alert').addClass('d-none');

    $.ajax({
        url:         `/api/events/${currentEvent.id}/apply`,
        type:        'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            fullName,
            email,
            phone:             $('#apply-phone').val().trim()   || null,
            birthDate:         $('#apply-birthdate').val()       || null,
            gender:            $('#apply-gender').val()          || null,
            ratingPoints:      parseInt($('#apply-rating').val()) || null,
            cfTurnstileResponse: turnstileToken
        }),
        beforeSend: xhr => xhr.setRequestHeader('X-XSRF-TOKEN', getCsrfToken()),
        success: (resp) => {
            showAlert('success', resp.message || 'Заявка принята! Ожидайте письма на почту.');
            $btn.html('<i class="bi bi-check-lg me-1"></i>Заявка принята').prop('disabled', true);
            clearApplyForm();
            setTimeout(() => {
                bootstrap.Modal.getInstance(document.getElementById('apply-event-modal'))?.hide();
            }, 2500);
        },
        error: (xhr) => {
            const msg = xhr.responseJSON?.message || 'Ошибка при подаче заявки. Попробуйте снова.';
            showAlert('danger', msg);
            if (window.turnstile && turnstileWidgetId !== null) {
                window.turnstile.reset(turnstileWidgetId);
            }
            turnstileToken = null;
            $btn.html(orig).prop('disabled', false);
        }
    });
}
