{% if not img_provider_writes_enabled %}
<div class="alert alert-warning py-2">
    Для управления API-ключами генерации изображений требуется <code>SESSION_ENCRYPTION_KEY</code>. Без него настройки доступны только для чтения.
</div>
{% endif %}

<form method="post" action="/settings/image-providers/add" class="row g-2 align-items-end mb-4" data-busy>
    <div class="col-12 col-md-6">
        <label for="img_provider_add" class="form-label">Добавить провайдера</label>
        <select id="img_provider_add" name="provider" class="form-select" {% if not img_provider_writes_enabled %}disabled{% endif %}>
            <option value="">Выберите провайдера</option>
            {% for spec in img_provider_options %}
            <option value="{{ spec.name }}">{{ spec.display_name }} ({{ spec.name }})</option>
            {% endfor %}
        </select>
    </div>
    <div class="col-12 col-md-auto">
        <button type="submit" class="btn btn-outline-primary btn-sm" {% if not img_provider_writes_enabled %}disabled{% endif %}>
            <i class="bi bi-plus-lg me-1"></i>Добавить
        </button>
    </div>
</form>

{% if img_provider_views %}
<form method="post" action="/settings/image-providers/save" data-busy>
    {% for item in img_provider_views %}
    <div class="card shadow-sm mb-3">
        <div class="card-body">
            <input type="hidden" name="img_provider_present__{{ item.provider }}" value="1">
            <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
                <div>
                    <div class="fw-semibold">{{ item.display_name }}</div>
                    <div class="small text-muted">
                        provider: <code>{{ item.provider }}</code>
                        {% if item.env_var_set %}
                        | <span class="badge text-bg-success">env</span> <code>{{ item.env_var_names }}</code>
                        {% endif %}
                    </div>
                </div>
                <button type="submit"
                        class="btn btn-outline-danger btn-sm"
                        formaction="/settings/image-providers/{{ item.provider }}/delete"
                        formmethod="post"
                        {% if not img_provider_writes_enabled %}disabled{% endif %}>
                    <i class="bi bi-trash me-1"></i>Удалить
                </button>
            </div>

            <div class="row g-3 mb-2">
                <div class="col-12 col-md-3">
                    <label class="form-label" for="img_provider_enabled__{{ item.provider }}">Статус</label>
                    <select class="form-select" id="img_provider_enabled__{{ item.provider }}"
                            name="img_provider_enabled__{{ item.provider }}" {% if not img_provider_writes_enabled %}disabled{% endif %}>
                        <option value="1" {{ 'selected' if item.enabled else '' }}>Enabled</option>
                        <option value="" {{ 'selected' if not item.enabled else '' }}>Disabled</option>
                    </select>
                </div>
                <div class="col-12 col-md-5">
                    <label class="form-label" for="img_provider_secret__{{ item.provider }}__api_key">API Key</label>
                    <input type="password" class="form-control"
                           id="img_provider_secret__{{ item.provider }}__api_key"
                           name="img_provider_secret__{{ item.provider }}__api_key"
                           placeholder="{{ '••••••••' if item.has_key else 'Введите API ключ' }}"
                           {% if not img_provider_writes_enabled %}disabled{% endif %}>
                    <div class="form-text">
                        {% if item.has_key %}Ключ сохранён и скрыт. Оставьте пустым, чтобы не менять.{% elif item.env_var_set %}Ключ из env будет использован как fallback.{% else %}Значение ещё не задано.{% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% endfor %}

    <div class="card shadow-sm mb-3">
        <div class="card-body">
            <label class="form-label fw-semibold">Модель по умолчанию</label>
            <div class="input-group mb-2">
                <input type="text" class="form-control" id="default-image-model"
                       name="default_image_model" value="{{ default_image_model }}" readonly
                       placeholder="Не выбрана — выберите из каталога ниже">
                <button type="button" class="btn btn-outline-secondary" id="clear-default-model"
                        title="Сбросить">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>
        </div>
    </div>

    <div class="card shadow-sm mb-3">
        <div class="card-body">
            <label class="form-label fw-semibold">Каталог моделей</label>
            <div class="row g-2 align-items-end mb-3">
                <div class="col-auto">
                    <select class="form-select" id="img-catalog-provider">
                        <option value="">Провайдер</option>
                        {% for item in img_provider_views %}
                        {% if item.enabled %}
                        <option value="{{ item.provider }}">{{ item.display_name }}</option>
                        {% endif %}
                        {% endfor %}
                    </select>
                </div>
                <div class="col">
                    <input type="text" id="img-catalog-query" class="form-control"
                           placeholder="flux, sdxl, dall-e...">
                </div>
                <div class="col-auto">
                    <button class="btn btn-outline-secondary" id="img-catalog-search-btn" type="button">
                        <i class="bi bi-search"></i>
                    </button>
                </div>
            </div>
            <div id="img-catalog-results" style="max-height:360px;overflow-y:auto"></div>
            <div id="img-catalog-spinner" class="text-center d-none">
                <div class="spinner-border spinner-border-sm text-secondary" role="status"></div>
            </div>
        </div>
    </div>

    <div class="d-flex justify-content-end">
        <button type="submit" class="btn btn-primary" {% if not img_provider_writes_enabled %}disabled{% endif %}>Сохранить</button>
    </div>
</form>

<script defer>
document.addEventListener('DOMContentLoaded', function() {
    var clearBtn = document.getElementById('clear-default-model');
    if (clearBtn) {
        clearBtn.addEventListener('click', function() {
            document.getElementById('default-image-model').value = '';
        });
    }

    var searchBtn = document.getElementById('img-catalog-search-btn');
    if (!searchBtn) return;
    var resultsDiv = document.getElementById('img-catalog-results');
    var spinner = document.getElementById('img-catalog-spinner');
    var providerSel = document.getElementById('img-catalog-provider');
    var queryInput = document.getElementById('img-catalog-query');

    searchBtn.addEventListener('click', async function() {
        var provider = providerSel.value;
        if (!provider) return;
        spinner.classList.remove('d-none');
        resultsDiv.innerHTML = '';
        try {
            var q = queryInput.value.trim();
            var url = '/images/models/search?provider=' + encodeURIComponent(provider) + '&q=' + encodeURIComponent(q);
            var resp = await fetch(url);
            var data = await resp.json();
            if (!data.ok || !data.models.length) {
                resultsDiv.innerHTML = '<p class="text-muted small">Ничего не найдено</p>';
                return;
            }
            var list = document.createElement('div');
            list.className = 'list-group list-group-flush';
            for (var i = 0; i < data.models.length; i++) {
                var m = data.models[i];
                var item = document.createElement('div');
                item.className = 'list-group-item d-flex justify-content-between align-items-start';

                var info = document.createElement('div');
                var title = document.createElement('div');
                title.className = 'fw-semibold small';
                title.textContent = m.id;
                info.appendChild(title);

                var desc = document.createElement('div');
                desc.className = 'text-muted small';
                desc.textContent = m.description || '';
                info.appendChild(desc);

                if (m.run_count) {
                    var badge = document.createElement('span');
                    badge.className = 'badge text-bg-secondary';
                    badge.textContent = m.run_count.toLocaleString() + ' runs';
                    info.appendChild(badge);
                }
                if (m.rank != null) {
                    var rankBadge = document.createElement('span');
                    rankBadge.className = 'badge text-bg-info ms-1';
                    rankBadge.textContent = 'rank ' + m.rank;
                    info.appendChild(rankBadge);
                }
                item.appendChild(info);

                var btn = document.createElement('button');
                btn.className = 'btn btn-outline-primary btn-sm ms-2';
                btn.setAttribute('data-model', m.model_string);
                btn.textContent = 'Выбрать';
                btn.type = 'button';
                btn.addEventListener('click', function() {
                    document.getElementById('default-image-model').value = this.dataset.model;
                });
                item.appendChild(btn);
                list.appendChild(item);
            }
            resultsDiv.innerHTML = '';
            resultsDiv.appendChild(list);
        } catch (err) {
            resultsDiv.innerHTML = '<p class="text-danger small">' + err.message + '</p>';
        } finally {
            spinner.classList.add('d-none');
        }
    });
});
</script>
{% else %}
<p class="text-muted mb-0">Провайдеры изображений ещё не добавлены.</p>
{% endif %}
