{% extends "page.html" %}
{% block page_content %}
<div class="card">
    <div class="card-header">
        <h2>🧪 Тест формул</h2>
        <a href="/service/coefficients" class="btn btn-secondary btn-sm">← Коэффициенты</a>
    </div>
    <div class="card-body">
        <div class="form-group">
            <label>Выберите формулу для тестирования</label>
            <select id="formula-select" onchange="switchFormula(this.value)" style="max-width:400px">
                {% for f in formulas %}
                <option value="{{ f.key }}" {% if f.key == selected %}selected{% endif %}>{{ f.name }}</option>
                {% endfor %}
            </select>
        </div>

        {% for f in formulas %}
        <div id="formula-{{ f.key }}" class="formula-test-panel" {% if f.key != selected %}style="display:none"{% endif %}>
            <div class="formula-description">
                <div style="margin-bottom:8px"><strong>Формула:</strong></div>
                <div class="formula-code">{{ f.formula }}</div>
                <div style="margin-top:8px"><strong>Результат:</strong> {{ f.result }}</div>
            </div>

            {% if f.sandbox %}
            <form class="formula-sandbox-form" onsubmit="return testFormula(event, '{{ f.key }}')">
                <h3 style="margin:16px 0 12px;font-size:14px;">Параметры расчёта</h3>
                <div class="formula-inputs">
                    {% for inp in f.sandbox.inputs %}
                    <div class="form-group">
                        <label>{{ inp.label }}</label>
                        {% if inp.type == "checkbox" %}
                        <input type="checkbox" name="{{ inp.key }}" value="1" style="width:20px;height:20px;accent-color:var(--accent)">
                        {% elif inp.type == "select" %}
                        <select name="{{ inp.key }}">
                            {% for ok, ol in inp.options.items() %}
                            <option value="{{ ok }}" {% if ok == inp.default %}selected{% endif %}>{{ ol }}</option>
                            {% endfor %}
                        </select>
                        {% else %}
                        <input type="number" name="{{ inp.key }}" value="{{ inp.default|default(0) }}" step="any">
                        {% endif %}
                    </div>
                    {% endfor %}
                </div>
                <button type="submit" class="btn btn-primary">Рассчитать</button>
                <div class="formula-result" id="result-{{ f.key }}" style="display:none"></div>
            </form>
            {% else %}
            <div class="empty-state" style="padding:24px 0">
                <p>Для этой формулы пока нет тестовой песочницы. Используйте коэффициенты на странице <a href="/service/coefficients">управления коэффициентами</a>.</p>
            </div>
            {% endif %}

            <h3 style="margin:20px 0 10px;font-size:13px;color:var(--text-muted)">Связанные коэффициенты</h3>
            <div class="table-wrap"><table><thead><tr><th>Ключ</th><th>Значение</th><th>Описание</th></tr></thead>
                <tbody>{% for c in f.coeffs %}<tr>
                    <td><code>{{ c.key }}</code></td>
                    <td><strong>{{ c.value }}</strong></td>
                    <td><small>{{ c.description }}</small></td>
                </tr>{% endfor %}</tbody></table>
            </div>
        </div>
        {% endfor %}
    </div>
</div>

<script>
function switchFormula(key) {
    document.querySelectorAll('.formula-test-panel').forEach(function(el) {
        el.style.display = 'none';
    });
    var panel = document.getElementById('formula-' + key);
    if (panel) panel.style.display = 'block';
    history.replaceState(null, '', '/service/coefficients/test?group=' + key);
}

function testFormula(event, key) {
    event.preventDefault();
    var form = event.target;
    var data = new URLSearchParams(new FormData(form));
    var resultBox = document.getElementById('result-' + key);
    resultBox.style.display = 'block';
    resultBox.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
    resultBox.className = 'formula-result';
    fetch('/service/coefficients/test/' + key, {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: data.toString()
    }).then(function(r) { return r.json() }).then(function(resp) {
        resultBox.textContent = 'Результат: ' + (resp.result || 'Ошибка');
        resultBox.className = 'formula-result formula-result-success';
    }).catch(function(err) {
        resultBox.textContent = 'Ошибка: ' + err.message;
        resultBox.className = 'formula-result formula-result-error';
    });
    return false;
}
</script>

<style>
.formula-test-panel { margin-top: 16px; }
.formula-description {
    background: var(--bg-input);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 16px;
    margin-bottom: 12px;
}
.formula-code {
    background: rgba(0,0,0,0.3);
    padding: 12px;
    border-radius: 8px;
    font-family: 'Consolas', 'Courier New', monospace;
    font-size: 13px;
    line-height: 1.6;
    white-space: pre-wrap;
    color: var(--accent);
}
.formula-inputs {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 12px;
    margin-bottom: 16px;
}
.formula-result {
    margin-top: 12px;
    padding: 12px 16px;
    border-radius: var(--radius);
    font-weight: 600;
    font-size: 14px;
}
.formula-result-success {
    background: rgba(34, 197, 94, 0.1);
    border: 1px solid var(--success);
    color: var(--success);
}
.formula-result-error {
    background: rgba(239, 68, 68, 0.1);
    border: 1px solid var(--danger);
    color: var(--danger);
}
</style>
{% endblock %}