<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>配置管理 - OpenClaw</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #0f1419;
            color: #e6e6e6;
            line-height: 1.6;
        }

        .header {
            background: linear-gradient(135deg, #1a2332 0%, #0f1419 100%);
            padding: 20px 30px;
            border-bottom: 1px solid #2d3a4a;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 24px;
            font-weight: 600;
            color: #00d4aa;
        }

        .nav-links {
            display: flex;
            gap: 20px;
        }

        .nav-link {
            color: #8b9aad;
            text-decoration: none;
            font-size: 14px;
            padding: 8px 16px;
            border-radius: 6px;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .nav-link:hover {
            color: #e6e6e6;
            background: #2d3a4a;
        }

        .nav-link.active {
            color: #00d4aa;
            background: rgba(0, 212, 170, 0.1);
        }

        .container {
            padding: 20px 30px;
            max-width: 1400px;
            margin: 0 auto;
        }

        .page-header {
            margin-bottom: 25px;
        }

        .page-header h2 {
            font-size: 20px;
            font-weight: 600;
            color: #fff;
            margin-bottom: 8px;
        }

        .page-header p {
            color: #8b9aad;
            font-size: 14px;
        }

        .config-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
            gap: 20px;
            margin-bottom: 25px;
        }

        @media (max-width: 600px) {
            .config-grid {
                grid-template-columns: 1fr;
            }
        }

        .card {
            background: #1a2332;
            border-radius: 12px;
            border: 1px solid #2d3a4a;
            overflow: hidden;
            transition: border-color 0.2s;
        }

        .card:hover {
            border-color: #3d4a5a;
        }

        .card-header {
            background: #222d3d;
            padding: 15px 20px;
            border-bottom: 1px solid #2d3a4a;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-title {
            font-size: 16px;
            font-weight: 600;
            color: #fff;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .card-icon {
            font-size: 18px;
        }

        .card-body {
            padding: 20px;
        }

        .form-group {
            margin-bottom: 18px;
        }

        .form-group:last-child {
            margin-bottom: 0;
        }

        .form-label {
            display: block;
            font-size: 13px;
            font-weight: 500;
            color: #8b9aad;
            margin-bottom: 6px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .form-input {
            width: 100%;
            padding: 10px 14px;
            background: #0f1419;
            border: 1px solid #2d3a4a;
            border-radius: 8px;
            color: #e6e6e6;
            font-size: 14px;
            transition: all 0.2s;
        }

        .form-input:focus {
            outline: none;
            border-color: #00d4aa;
            box-shadow: 0 0 0 3px rgba(0, 212, 170, 0.1);
        }

        .form-input::placeholder {
            color: #5a6a7a;
        }

        .form-input:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        select.form-input {
            cursor: pointer;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%238b9aad' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 14px center;
            padding-right: 36px;
        }

        .form-hint {
            font-size: 12px;
            color: #5a6a7a;
            margin-top: 4px;
        }

        .form-error {
            font-size: 12px;
            color: #ff4444;
            margin-top: 4px;
            display: none;
        }

        .form-group.has-error .form-input {
            border-color: #ff4444;
        }

        .form-group.has-error .form-error {
            display: block;
        }

        .input-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
            gap: 15px;
        }

        .input-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .input-prefix {
            color: #8b9aad;
            font-size: 14px;
        }

        .provider-section {
            background: #0f1419;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            border: 1px solid #2d3a4a;
        }

        .provider-section:last-child {
            margin-bottom: 0;
        }

        .provider-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 12px;
            font-weight: 600;
            color: #fff;
            font-size: 14px;
        }

        .provider-icon {
            width: 20px;
            height: 20px;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
        }

        .provider-icon.openai {
            background: #10a37f;
            color: #fff;
        }

        .provider-icon.anthropic {
            background: #d4a574;
            color: #1a1a1a;
        }

        .actions-bar {
            background: #1a2332;
            border-radius: 12px;
            border: 1px solid #2d3a4a;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 30px;
        }

        .btn {
            padding: 10px 24px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            border: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .btn-primary {
            background: #00d4aa;
            color: #0f1419;
        }

        .btn-primary:hover:not(:disabled) {
            background: #00e6b8;
            box-shadow: 0 4px 15px rgba(0, 212, 170, 0.3);
        }

        .btn-secondary {
            background: #2d3a4a;
            color: #e6e6e6;
        }

        .btn-secondary:hover:not(:disabled) {
            background: #3d4a5a;
        }

        .btn-danger {
            background: #ff4444;
            color: #fff;
        }

        .btn-danger:hover:not(:disabled) {
            background: #ff5555;
        }

        .btn-group {
            display: flex;
            gap: 10px;
        }

        .status-message {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
        }

        .status-message.success {
            color: #00d4aa;
        }

        .status-message.error {
            color: #ff4444;
        }

        .status-message.loading {
            color: #ffc107;
        }

        .spinner {
            width: 16px;
            height: 16px;
            border: 2px solid currentColor;
            border-right-color: transparent;
            border-radius: 50%;
            animation: spin 0.75s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .alert-container {
            position: fixed;
            top: 80px;
            right: 20px;
            width: 350px;
            z-index: 1000;
        }

        .alert {
            background: #1a2332;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 10px;
            border-left: 4px solid;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
            animation: slideIn 0.3s ease-out;
        }

        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }

        .alert-success { border-color: #00d4aa; }
        .alert-error { border-color: #ff4444; }
        .alert-warning { border-color: #ffc107; }

        .alert-title {
            font-weight: 600;
            margin-bottom: 5px;
            color: #fff;
        }

        .alert-message {
            font-size: 13px;
            color: #8b9aad;
        }

        .section-divider {
            height: 1px;
            background: #2d3a4a;
            margin: 15px 0;
        }

        .readonly-field {
            background: #1a2332 !important;
            color: #5a6a7a !important;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🦀 OpenClaw 交易仪表盘</h1>
        <div class="nav-links" style="display: flex; gap: 20px; align-items: center;">
            <a href="/" style="color: #8b9aad; text-decoration: none; font-weight: 500;">仪表盘</a>
            <a href="/orders" style="color: #8b9aad; text-decoration: none; font-weight: 500;">订单</a>
            <a href="/config" style="color: #00d4aa; text-decoration: none; font-weight: 500;">配置</a>
            <a href="/exchanges" style="color: #8b9aad; text-decoration: none; font-weight: 500;">交易所</a>
        </div>
        <div class="connection-status">
            <span class="status-dot" id="statusDot"></span>
            <span id="statusText">连接中...</span>
        </div>
    </div>

    <div class="alert-container" id="alertContainer"></div>

    <div class="container">
        <div class="page-header">
            <h2>配置管理</h2>
            <p>管理系统设置、成本、阈值和 LLM 提供商配置。</p>
        </div>

        <div class="actions-bar">
            <div id="statusArea">
                <span class="status-message" id="statusText">准备保存更改</span>
            </div>
            <div class="btn-group">
                <button type="button" class="btn btn-secondary" id="resetBtn" onclick="resetForm()">
                    <span>重置</span>
                </button>
                <button type="button" class="btn btn-primary" id="saveBtn" onclick="saveConfig()">
                    <span>保存配置</span>
                </button>
            </div>
        </div>

        <form id="configForm">
            <div class="config-grid">
                <!-- Initial Capital Section -->
                <div class="card">
                    <div class="card-header">
                        <span class="card-title">
                            <span class="card-icon">$</span>
                            初始资本
                        </span>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label class="form-label" for="capital_trader">交易代理</label>
                            <div class="input-group">
                                <span class="input-prefix">$</span>
                                <input type="number" id="capital_trader" name="initial_capital.trader" class="form-input" value="10000" min="1" step="100">
                            </div>
                            <div class="form-hint">交易代理的起始资本</div>
                            <div class="form-error">必须是正数</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="capital_analyst">分析师代理</label>
                            <div class="input-group">
                                <span class="input-prefix">$</span>
                                <input type="number" id="capital_analyst" name="initial_capital.analyst" class="form-input" value="5000" min="1" step="100">
                            </div>
                            <div class="form-hint">分析代理的起始资本</div>
                            <div class="form-error">必须是正数</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="capital_risk_manager">风险管理器</label>
                            <div class="input-group">
                                <span class="input-prefix">$</span>
                                <input type="number" id="capital_risk_manager" name="initial_capital.risk_manager" class="form-input" value="5000" min="1" step="100">
                            </div>
                            <div class="form-hint">风险管理的起始资本</div>
                            <div class="form-error">必须是正数</div>
                        </div>
                    </div>
                </div>

                <!-- Cost Structure Section -->
                <div class="card">
                    <div class="card-header">
                        <span class="card-title">
                            <span class="card-icon">C</span>
                            成本结构
                        </span>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label class="form-label" for="llm_input_cost">LLM 输入成本（每百万 token）</label>
                            <div class="input-group">
                                <span class="input-prefix">$</span>
                                <input type="number" id="llm_input_cost" name="cost_structure.llm_input_per_1m" class="form-input" value="2.5" min="0.01" step="0.1">
                            </div>
                            <div class="form-hint">每百万输入 token 的成本</div>
                            <div class="form-error">必须大于 0</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="llm_output_cost">LLM 输出成本（每百万 token）</label>
                            <div class="input-group">
                                <span class="input-prefix">$</span>
                                <input type="number" id="llm_output_cost" name="cost_structure.llm_output_per_1m" class="form-input" value="10.0" min="0.01" step="0.1">
                            </div>
                            <div class="form-hint">每百万输出 token 的成本</div>
                            <div class="form-error">必须大于 0</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="market_data_cost">市场数据成本（每次调用）</label>
                            <div class="input-group">
                                <span class="input-prefix">$</span>
                                <input type="number" id="market_data_cost" name="cost_structure.market_data_per_call" class="form-input" value="0.01" min="0" step="0.001">
                            </div>
                            <div class="form-hint">每次市场数据 API 调用的成本</div>
                            <div class="form-error">必须为非负数</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="trade_fee_rate">交易费率</label>
                            <div class="input-group">
                                <input type="number" id="trade_fee_rate" name="cost_structure.trade_fee_rate" class="form-input" value="0.001" min="0" max="1" step="0.0001">
                                <span class="input-prefix">（小数）</span>
                            </div>
                            <div class="form-hint">小数形式费率（0.001 = 0.1%）</div>
                            <div class="form-error">必须在 0 到 1 之间</div>
                        </div>
                    </div>
                </div>

                <!-- Survival Thresholds Section -->
                <div class="card">
                    <div class="card-header">
                        <span class="card-title">
                            <span class="card-icon">T</span>
                            生存阈值
                        </span>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label class="form-label" for="thriving_mult">繁荣倍数</label>
                            <input type="number" id="thriving_mult" name="survival_thresholds.thriving_multiplier" class="form-input" value="3.0" min="1.01" step="0.1">
                            <div class="form-hint">"繁荣"状态的组合价值倍数（例如，3.0 = 3倍资本）</div>
                            <div class="form-error">必须大于 1</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="stable_mult">稳定倍数</label>
                            <input type="number" id="stable_mult" name="survival_thresholds.stable_multiplier" class="form-input" value="1.5" min="1.01" step="0.1">
                            <div class="form-hint">"稳定"状态的组合价值倍数</div>
                            <div class="form-error">必须大于 1 且小于繁荣倍数</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="struggling_mult">挣扎倍数</label>
                            <input type="number" id="struggling_mult" name="survival_thresholds.struggling_multiplier" class="form-input" value="0.8" min="0.01" max="0.99" step="0.05">
                            <div class="form-hint">"挣扎"状态的组合价值倍数</div>
                            <div class="form-error">必须小于稳定倍数</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="bankrupt_mult">破产倍数</label>
                            <input type="number" id="bankrupt_mult" name="survival_thresholds.bankrupt_multiplier" class="form-input" value="0.1" min="0" max="0.99" step="0.05">
                            <div class="form-hint">"破产"状态的组合价值倍数</div>
                            <div class="form-error">必须小于挣扎倍数</div>
                        </div>
                    </div>
                </div>

                <!-- Simulation Settings Section -->
                <div class="card">
                    <div class="card-header">
                        <span class="card-title">
                            <span class="card-icon">S</span>
                            模拟设置
                        </span>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label class="form-label" for="simulation_days">模拟天数</label>
                            <input type="number" id="simulation_days" name="simulation_days" class="form-input" value="30" min="1" step="1">
                            <div class="form-hint">默认模拟持续时间（交易日）</div>
                            <div class="form-error">必须是正整数</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="data_dir">数据目录</label>
                            <input type="text" id="data_dir" name="data_dir" class="form-input" value="./data">
                            <div class="form-hint">数据存储目录</div>
                            <div class="form-error">无效路径</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="log_level">日志级别</label>
                            <select id="log_level" name="log_level" class="form-input">
                                <option value="DEBUG">DEBUG</option>
                                <option value="INFO" selected>INFO</option>
                                <option value="WARNING">WARNING</option>
                                <option value="ERROR">ERROR</option>
                                <option value="CRITICAL">CRITICAL</option>
                            </select>
                            <div class="form-hint">日志详细程度级别</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- LLM Providers Section (Full Width) -->
            <div class="card" style="margin-bottom: 30px;">
                <div class="card-header">
                    <span class="card-title">
                        <span class="card-icon">L</span>
                        LLM 提供商
                    </span>
                </div>
                <div class="card-body">
                    <div class="config-grid" style="margin-bottom: 0;">
                        <!-- OpenAI Configuration -->
                        <div class="provider-section">
                            <div class="provider-header">
                                <span class="provider-icon openai">O</span>
                                OpenAI 配置
                            </div>
                            <div class="form-group">
                                <label class="form-label" for="openai_model">模型</label>
                                <input type="text" id="openai_model" name="llm_providers.openai.model" class="form-input" value="gpt-4o">
                            </div>
                            <div class="form-group">
                                <label class="form-label" for="openai_api_key">API 密钥</label>
                                <input type="password" id="openai_api_key" name="llm_providers.openai.api_key" class="form-input" placeholder="通过环境变量设置">
                                <div class="form-hint">留空则使用 OPENCLAW_LLM_PROVIDERS__OPENAI__API_KEY 环境变量</div>
                            </div>
                            <div class="form-group">
                                <label class="form-label" for="openai_base_url">基础 URL（可选）</label>
                                <input type="text" id="openai_base_url" name="llm_providers.openai.base_url" class="form-input" placeholder="https://api.openai.com/v1">
                            </div>
                            <div class="input-row">
                                <div class="form-group">
                                    <label class="form-label" for="openai_temperature">温度</label>
                                    <input type="number" id="openai_temperature" name="llm_providers.openai.temperature" class="form-input" value="0.7" min="0" max="2" step="0.1">
                                </div>
                                <div class="form-group">
                                    <label class="form-label" for="openai_max_tokens">最大 token 数</label>
                                    <input type="number" id="openai_max_tokens" name="llm_providers.openai.max_tokens" class="form-input" placeholder="无限制">
                                </div>
                                <div class="form-group">
                                    <label class="form-label" for="openai_timeout">超时（秒）</label>
                                    <input type="number" id="openai_timeout" name="llm_providers.openai.timeout" class="form-input" value="30" min="1" step="1">
                                </div>
                            </div>
                        </div>

                        <!-- Anthropic Configuration -->
                        <div class="provider-section">
                            <div class="provider-header">
                                <span class="provider-icon anthropic">A</span>
                                Anthropic 配置
                            </div>
                            <div class="form-group">
                                <label class="form-label" for="anthropic_model">模型</label>
                                <input type="text" id="anthropic_model" name="llm_providers.anthropic.model" class="form-input" value="claude-3-5-sonnet-20241022">
                            </div>
                            <div class="form-group">
                                <label class="form-label" for="anthropic_api_key">API 密钥</label>
                                <input type="password" id="anthropic_api_key" name="llm_providers.anthropic.api_key" class="form-input" placeholder="通过环境变量设置">
                                <div class="form-hint">留空则使用 OPENCLAW_LLM_PROVIDERS__ANTHROPIC__API_KEY 环境变量</div>
                            </div>
                            <div class="form-group">
                                <label class="form-label" for="anthropic_base_url">基础 URL（可选）</label>
                                <input type="text" id="anthropic_base_url" name="llm_providers.anthropic.base_url" class="form-input" placeholder="https://api.anthropic.com">
                            </div>
                            <div class="input-row">
                                <div class="form-group">
                                    <label class="form-label" for="anthropic_temperature">温度</label>
                                    <input type="number" id="anthropic_temperature" name="llm_providers.anthropic.temperature" class="form-input" value="0.7" min="0" max="2" step="0.1">
                                </div>
                                <div class="form-group">
                                    <label class="form-label" for="anthropic_max_tokens">最大 token 数</label>
                                    <input type="number" id="anthropic_max_tokens" name="llm_providers.anthropic.max_tokens" class="form-input" placeholder="无限制">
                                </div>
                                <div class="form-group">
                                    <label class="form-label" for="anthropic_timeout">超时（秒）</label>
                                    <input type="number" id="anthropic_timeout" name="llm_providers.anthropic.timeout" class="form-input" value="30" min="1" step="1">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <script>
        // Store original values for reset functionality
        var originalValues = {};

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            // Save original values
            var inputs = document.querySelectorAll('.form-input');
            inputs.forEach(function(input) {
                originalValues[input.id] = input.value;
            });

            // Load current config from server
            loadConfig();
        });

        // Load configuration from server
        function loadConfig() {
            fetch('/api/config')
                .then(function(response) {
                    if (response.ok) {
                        return response.json();
                    }
                    throw new Error('加载配置失败');
                })
                .then(function(config) {
                    populateForm(config);
                })
                .catch(function(error) {
                    console.log('使用默认配置');
                });
        }

        // Populate form with config data
        function populateForm(config) {
            if (config.initial_capital) {
                setValue('capital_trader', config.initial_capital.trader);
                setValue('capital_analyst', config.initial_capital.analyst);
                setValue('capital_risk_manager', config.initial_capital.risk_manager);
            }

            if (config.cost_structure) {
                setValue('llm_input_cost', config.cost_structure.llm_input_per_1m);
                setValue('llm_output_cost', config.cost_structure.llm_output_per_1m);
                setValue('market_data_cost', config.cost_structure.market_data_per_call);
                setValue('trade_fee_rate', config.cost_structure.trade_fee_rate);
            }

            if (config.survival_thresholds) {
                setValue('thriving_mult', config.survival_thresholds.thriving_multiplier);
                setValue('stable_mult', config.survival_thresholds.stable_multiplier);
                setValue('struggling_mult', config.survival_thresholds.struggling_multiplier);
                setValue('bankrupt_mult', config.survival_thresholds.bankrupt_multiplier);
            }

            if (config.llm_providers) {
                if (config.llm_providers.openai) {
                    setValue('openai_model', config.llm_providers.openai.model);
                    setValue('openai_api_key', config.llm_providers.openai.api_key);
                    setValue('openai_base_url', config.llm_providers.openai.base_url);
                    setValue('openai_temperature', config.llm_providers.openai.temperature);
                    setValue('openai_max_tokens', config.llm_providers.openai.max_tokens);
                    setValue('openai_timeout', config.llm_providers.openai.timeout);
                }
                if (config.llm_providers.anthropic) {
                    setValue('anthropic_model', config.llm_providers.anthropic.model);
                    setValue('anthropic_api_key', config.llm_providers.anthropic.api_key);
                    setValue('anthropic_base_url', config.llm_providers.anthropic.base_url);
                    setValue('anthropic_temperature', config.llm_providers.anthropic.temperature);
                    setValue('anthropic_max_tokens', config.llm_providers.anthropic.max_tokens);
                    setValue('anthropic_timeout', config.llm_providers.anthropic.timeout);
                }
            }

            setValue('simulation_days', config.simulation_days);
            setValue('data_dir', config.data_dir);
            setValue('log_level', config.log_level);

            // Update original values after loading
            var inputs = document.querySelectorAll('.form-input');
            inputs.forEach(function(input) {
                originalValues[input.id] = input.value;
            });
        }

        function setValue(id, value) {
            var element = document.getElementById(id);
            if (element && value !== undefined && value !== null) {
                element.value = value;
            }
        }

        // Collect form data into config object
        function collectFormData() {
            return {
                initial_capital: {
                    trader: parseFloat(document.getElementById('capital_trader').value),
                    analyst: parseFloat(document.getElementById('capital_analyst').value),
                    risk_manager: parseFloat(document.getElementById('capital_risk_manager').value)
                },
                cost_structure: {
                    llm_input_per_1m: parseFloat(document.getElementById('llm_input_cost').value),
                    llm_output_per_1m: parseFloat(document.getElementById('llm_output_cost').value),
                    market_data_per_call: parseFloat(document.getElementById('market_data_cost').value),
                    trade_fee_rate: parseFloat(document.getElementById('trade_fee_rate').value)
                },
                survival_thresholds: {
                    thriving_multiplier: parseFloat(document.getElementById('thriving_mult').value),
                    stable_multiplier: parseFloat(document.getElementById('stable_mult').value),
                    struggling_multiplier: parseFloat(document.getElementById('struggling_mult').value),
                    bankrupt_multiplier: parseFloat(document.getElementById('bankrupt_mult').value)
                },
                llm_providers: {
                    openai: {
                        model: document.getElementById('openai_model').value,
                        api_key: document.getElementById('openai_api_key').value || null,
                        base_url: document.getElementById('openai_base_url').value || null,
                        temperature: parseFloat(document.getElementById('openai_temperature').value),
                        max_tokens: parseInt(document.getElementById('openai_max_tokens').value) || null,
                        timeout: parseInt(document.getElementById('openai_timeout').value)
                    },
                    anthropic: {
                        model: document.getElementById('anthropic_model').value,
                        api_key: document.getElementById('anthropic_api_key').value || null,
                        base_url: document.getElementById('anthropic_base_url').value || null,
                        temperature: parseFloat(document.getElementById('anthropic_temperature').value),
                        max_tokens: parseInt(document.getElementById('anthropic_max_tokens').value) || null,
                        timeout: parseInt(document.getElementById('anthropic_timeout').value)
                    }
                },
                simulation_days: parseInt(document.getElementById('simulation_days').value),
                data_dir: document.getElementById('data_dir').value,
                log_level: document.getElementById('log_level').value
            };
        }

        // Validate form
        function validateForm() {
            var isValid = true;
            var inputs = document.querySelectorAll('.form-input[type="number"]');

            inputs.forEach(function(input) {
                var group = input.closest('.form-group');
                if (group) {
                    group.classList.remove('has-error');
                }

                if (input.type === 'number' && input.value !== '') {
                    var value = parseFloat(input.value);
                    var min = parseFloat(input.min);
                    var max = parseFloat(input.max);

                    if (isNaN(value)) {
                        if (group) group.classList.add('has-error');
                        isValid = false;
                    } else if (!isNaN(min) && value < min) {
                        if (group) group.classList.add('has-error');
                        isValid = false;
                    } else if (!isNaN(max) && value > max) {
                        if (group) group.classList.add('has-error');
                        isValid = false;
                    }
                }
            });

            // Validate threshold ordering
            var thriving = parseFloat(document.getElementById('thriving_mult').value);
            var stable = parseFloat(document.getElementById('stable_mult').value);
            var struggling = parseFloat(document.getElementById('struggling_mult').value);
            var bankrupt = parseFloat(document.getElementById('bankrupt_mult').value);

            if (stable >= thriving) {
                document.getElementById('stable_mult').closest('.form-group').classList.add('has-error');
                isValid = false;
            }
            if (struggling >= stable) {
                document.getElementById('struggling_mult').closest('.form-group').classList.add('has-error');
                isValid = false;
            }
            if (bankrupt >= struggling) {
                document.getElementById('bankrupt_mult').closest('.form-group').classList.add('has-error');
                isValid = false;
            }

            return isValid;
        }

        // Save configuration
        function saveConfig() {
            if (!validateForm()) {
                showAlert('验证错误', '请在保存前修复表单中的错误。', 'error');
                return;
            }

            var saveBtn = document.getElementById('saveBtn');
            var resetBtn = document.getElementById('resetBtn');
            var statusArea = document.getElementById('statusArea');

            saveBtn.disabled = true;
            resetBtn.disabled = true;
            statusArea.innerHTML = '<span class="status-message loading"><div class="spinner"></div> 正在保存配置...</span>';

            var config = collectFormData();

            fetch('/api/config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(config)
            })
            .then(function(response) {
                if (response.ok) {
                    return response.json();
                }
                return response.json().then(function(err) {
                    throw new Error(err.detail || '保存配置失败');
                });
            })
            .then(function() {
                statusArea.innerHTML = '<span class="status-message success">配置保存成功</span>';
                showAlert('成功', '配置已成功保存。', 'success');

                // Update original values
                var inputs = document.querySelectorAll('.form-input');
                inputs.forEach(function(input) {
                    originalValues[input.id] = input.value;
                });
            })
            .catch(function(error) {
                statusArea.innerHTML = '<span class="status-message error">保存配置失败</span>';
                showAlert('错误', error.message || '保存配置失败，请重试。', 'error');
            })
            .finally(function() {
                saveBtn.disabled = false;
                resetBtn.disabled = false;
            });
        }

        // Reset form to original values
        function resetForm() {
            Object.keys(originalValues).forEach(function(id) {
                var element = document.getElementById(id);
                if (element) {
                    element.value = originalValues[id];
                    var group = element.closest('.form-group');
                    if (group) {
                        group.classList.remove('has-error');
                    }
                }
            });

            document.getElementById('statusArea').innerHTML = '<span class="status-message">表单已重置为上次保存的值</span>';
            showAlert('重置', '表单已重置为上次保存的值。', 'warning');
        }

        // Show alert notification
        function showAlert(title, message, level) {
            var container = document.getElementById('alertContainer');
            var alert = document.createElement('div');
            alert.className = 'alert alert-' + level;

            var titleDiv = document.createElement('div');
            titleDiv.className = 'alert-title';
            titleDiv.textContent = title;

            var messageDiv = document.createElement('div');
            messageDiv.className = 'alert-message';
            messageDiv.textContent = message;

            alert.appendChild(titleDiv);
            alert.appendChild(messageDiv);
            container.appendChild(alert);

            setTimeout(function() {
                alert.style.animation = 'slideIn 0.3s ease-out reverse';
                setTimeout(function() { alert.remove(); }, 300);
            }, level === 'error' ? 8000 : 5000);
        }
    </script>
</body>
</html>
