<?php
$config = require __DIR__ . '/config.php';
require __DIR__ . '/functions.php';

try {
    if (!empty($_GET['target'])) {
        [$target, $targetHost] = tvc_validate_target($_GET['target'], $config['allowed_hosts']);
        $state = tvc_create_state($config, $target, $targetHost);
        header('Location: /?state=' . urlencode($state), true, 302);
        exit;
    }
    $state = $_GET['state'] ?? '';
    $stateData = tvc_read_state($config, $state);
    $targetHost = $stateData['host'];
} catch (Throwable $e) {
    http_response_code(400);
    echo htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
    exit;
}

$front = $config['aliyun_frontend'];
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="icon" href="data:,">
    <title>安全验证</title>
    <script>
        window.AliyunCaptchaConfig = {
            region: '<?= htmlspecialchars($front['region'], ENT_QUOTES, 'UTF-8') ?>',
            prefix: '<?= htmlspecialchars($front['prefix'], ENT_QUOTES, 'UTF-8') ?>'
        };
    </script>
    <script src="https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js"></script>
    <style>
        * { box-sizing: border-box; }
        body {
            margin: 0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f6f7fb;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, "PingFang SC", "Microsoft YaHei", sans-serif;
            color: #222;
        }
        .card {
            width: min(92vw, 420px);
            padding: 32px 24px;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 12px 40px rgba(0,0,0,.08);
            text-align: center;
        }
        h1 { margin: 0 0 10px; font-size: 22px; }
        p { margin: 0 0 24px; color: #666; font-size: 14px; line-height: 1.6; }
        .error { margin: 0 0 16px; color: #d4380d; font-size: 14px; line-height: 1.5; }
        /* 阿里云验证码渲染容器 */
        #captcha-element { display: flex; justify-content: center; margin-bottom: 20px; min-height: 44px; }
        button {
            width: 100%; height: 44px; border: 0; border-radius: 10px;
            background: #1677ff; color: #fff; font-size: 15px; cursor: pointer;
        }
        button:active { opacity: .85; }
        button:disabled { background: #c9cdd4; color: #fff; cursor: not-allowed; opacity: 1; }
        button:disabled:active { opacity: 1; }
        .host { color: #999; font-size: 12px; margin-top: 16px; word-break: break-all; }
    </style>
</head>
<body>
<div class="card">
    <h1>安全验证</h1>
    <p>请完成验证后继续访问</p>
    <div id="errorBox" class="error" style="display:none;"></div>
    <div id="captcha-element"></div>
    <button id="captcha-button" type="button">开始验证</button>
    <div class="host">验证完成后将进入页面</div>
</div>

<script>
    var STATE = '<?= htmlspecialchars($state, ENT_QUOTES, 'UTF-8') ?>';
    var SCENE_ID = '<?= htmlspecialchars($front['scene_id'], ENT_QUOTES, 'UTF-8') ?>';
    var bizCallbackUrl = null;
    var errorBox = document.getElementById('errorBox');

    function showError(msg) {
        errorBox.textContent = msg;
        errorBox.style.display = 'block';
    }
    function clearError() {
        errorBox.style.display = 'none';
    }

    async function captchaVerifyCallback(captchaVerifyParam) {
        clearError();
        try {
            var resp = await fetch('/verify.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ state: STATE, captchaVerifyParam: captchaVerifyParam })
            });
            var data = await resp.json();
            bizCallbackUrl = data.callback_url || null;
            if (!data.captchaResult && data.message) {
                showError(data.message);
            }
            return { captchaResult: !!data.captchaResult, bizResult: !!data.bizResult };
        } catch (e) {
            showError('网络异常，请重试');
            return { captchaResult: false, bizResult: false };
        }
    }

    function onBizResultCallback() {
        if (bizCallbackUrl) {
            window.location.href = bizCallbackUrl;
        } else {
            showError('验证结果已失效，请重新验证');
        }
    }

    function bootCaptcha() {
        if (typeof initAliyunCaptcha !== 'function') {
            showError('验证码脚本加载失败，请刷新页面');
            return;
        }
        initAliyunCaptcha({
            SceneId: SCENE_ID,
            mode: 'popup',
            element: '#captcha-element',
            button: '#captcha-button',
            captchaVerifyCallback: captchaVerifyCallback,
            onBizResultCallback: onBizResultCallback,
            slideStyle: { width: 360, height: 40 },
            language: 'cn',
            getInstance: function (instance) { window.captchaInstance = instance; }
        });
    }

    if (document.readyState === 'complete' || document.readyState === 'interactive') {
        bootCaptcha();
    } else {
        window.addEventListener('DOMContentLoaded', bootCaptcha);
    }
</script>

</body>
</html>
