<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Проверка доступа</title>
    <!-- Без onload, используем render=explicit -->
    <script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit" async defer></script>
    <style>
        body {margin:0; height:100vh; display:flex; align-items:center; justify-content:center; background:#f0f2f5; font-family:system-ui;}
        .card {background:white; padding:50px; border-radius:16px; box-shadow:0 10px 40px rgba(0,0,0,0.2); text-align:center; max-width:480px;}
        h1 {color:#1a3c6d; margin-bottom:0.5em;}
        p {color:#444; margin-bottom:2em;}
        #turnstile-container {margin:2em 0; min-height:78px;}
        button {padding:14px 50px; font-size:1.2em; background:#1e88e5; color:white; border:none; border-radius:10px; cursor:pointer;}
        button:hover {background:#1565c0;}
        button:disabled {background:#aaa; cursor:not-allowed;}
    </style>
</head>
<body>
    <div class="card">
        <h1>Проверка</h1>
        <p>Пройдите быструю проверку и заходите на сайт:</p>
        
        <div id="turnstile-container"></div>
        
        <button id="submit-btn" disabled>Продолжить</button>
        
        <p style="margin-top:2em; font-size:0.9em; color:#666;">Мы заботимся о безопасности</p>
    </div>

    <script>
        // Ждём, когда turnstile станет доступен (после загрузки api.js)
        function initTurnstile() {
            if (typeof turnstile === 'undefined') {
                setTimeout(initTurnstile, 200); // повторяем попытку
                return;
            }

            turnstile.render('#turnstile-container', {
                sitekey: '0x4AAAAAACJWntPJW7RYCaVy',  // ← ← ← СРОЧНО замени на СВОЙ реальный sitekey!
                callback: function(token) {
                    document.getElementById('submit-btn').disabled = false;
                    document.getElementById('submit-btn').onclick = function() {
                        fetch('/verify-turnstile.php', {
                            method: 'POST',
                            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                            body: 'cf-turnstile-response=' + encodeURIComponent(token)
                        })
                        .then(res => res.json())
                        .then(data => {
                            if (data.success) {
                                window.location.href = '/';
                            } else {
                                alert('Проверка не пройдена: ' + (data.error || 'Попробуйте снова'));
                            }
                        })
                        .catch(err => alert('Ошибка: ' + err.message));
                    };
                },
                'error-callback': function(errorCode) {
                    alert('Ошибка Turnstile: ' + errorCode);
                },
                theme: 'auto'
            });
        }

        // Запускаем после загрузки DOM
        if (document.readyState === 'complete' || document.readyState === 'interactive') {
            initTurnstile();
        } else {
            document.addEventListener('DOMContentLoaded', initTurnstile);
        }
    </script>
</body>
</html>