<!--
Copyright (C) 2026 Stefy Lanza <stefy@nexlab.net>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
-->
{% extends "base.html" %}

{% block title %}My Autoselects - AISBF{% endblock %}

{% block content %}
<h2 style="margin-bottom: 30px;">My Autoselect Configuration</h2>

{% if success %}
<div class="alert alert-success">{{ success }}</div>
{% endif %}

{% if error %}
<div class="alert alert-error">{{ error }}</div>
{% endif %}

<div id="autoselect-list" style="margin-bottom: 20px;">
    <!-- Autoselect list will be rendered here -->
</div>

<button type="button" class="btn" onclick="addAutoselect()" style="margin-top: 20px;">Add Autoselect</button>
<div style="display: flex; gap: 10px; margin-top: 20px;">
    <button type="button" class="btn" onclick="saveAutoselect()">Save Configuration</button>
    <a href="{{ url_for(request, '/dashboard') }}" class="btn btn-secondary">Cancel</a>
</div>

<script>
function escHtml(s) {
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}
const escHtmlAttr = escHtml;

async function apiCall(method, url, body) {
    const opts = { method, headers: { 'Content-Type': 'application/json' } };
    if (body !== undefined) opts.body = JSON.stringify(body);
    const r = await fetch(url, opts);
    return r.json();
}

// ===== Model Search Modal =====
let _msAllItems = [], _msDispItems = [], _msCancelled = false, _msCallback = null;

function _msEnsure() {
    if (document.getElementById('ms-overlay')) return;
    const d = document.createElement('div');
    d.id = 'ms-overlay';
    d.style.cssText = 'display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.75);z-index:9999;align-items:center;justify-content:center;';
    d.innerHTML = `
      <div style="background:#1a1a2e;border:1px solid #0f3460;border-radius:8px;padding:24px;max-width:560px;width:93%;max-height:85vh;display:flex;flex-direction:column;box-shadow:0 8px 32px rgba(0,0,0,0.6);">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
          <h3 id="ms-title" style="margin:0;font-size:16px;color:#e0e0e0;"></h3>
          <button type="button" onclick="msClose()" style="background:none;border:none;color:#a0a0a0;cursor:pointer;font-size:22px;padding:0 4px;">&times;</button>
        </div>
        <div id="ms-status" style="font-size:13px;color:#a0a0a0;min-height:18px;margin-bottom:10px;"></div>
        <div style="display:flex;gap:8px;margin-bottom:12px;">
          <input type="text" id="ms-filter-input" placeholder="Filter results…"
            style="flex:1;padding:8px;border:1px solid #0f3460;border-radius:3px;background:#16213e;color:#e0e0e0;font-size:14px;"
            onkeydown="if(event.key==='Enter')msFilter()">
          <button type="button" onclick="msFilter()" class="btn btn-secondary" style="padding:8px 14px;font-size:13px;">Filter</button>
        </div>
        <div id="ms-results" style="overflow-y:auto;flex:1;max-height:340px;border:1px solid #0f3460;border-radius:3px;background:#16213e;min-height:40px;"></div>
        <div style="margin-top:14px;display:flex;justify-content:flex-end;">
          <button type="button" onclick="msClose()" class="btn btn-secondary">Cancel</button>
        </div>
      </div>`;
    document.body.appendChild(d);
}

async function msOpenAll(inputId, cb) {
    _msEnsure(); _msCancelled = false; _msAllItems = []; _msDispItems = [];
    _msCallback = function(v) { const e = document.getElementById(inputId); if (e) e.value = v; cb(v); };
    const o = document.getElementById('ms-overlay'); o.style.display = 'flex';
    document.getElementById('ms-title').textContent = 'Search Models';
    document.getElementById('ms-filter-input').value = '';
    const all = availableRotations.map(r => ({id: r, name: r + ' (rotation)'})).concat(availableModels);
    if (all.length) {
        _msAllItems = all;
        document.getElementById('ms-status').textContent = all.length + ' model(s) available. Use Filter to narrow results.';
        msRenderResults(all);
    } else {
        document.getElementById('ms-status').textContent = 'No models loaded — fetching from provider APIs…';
        document.getElementById('ms-results').innerHTML = '<p style="color:#a0a0a0;text-align:center;padding:20px;">Loading…</p>';
        try {
            const r = await fetch('/dashboard/search-all-models?refresh=true');
            if (_msCancelled) return;
            const data = await r.json(); const fetched = data.models || [];
            _msAllItems = fetched;
            availableModels = fetched.filter(m => m.type === 'provider');
            document.getElementById('ms-status').textContent = fetched.length ? fetched.length + ' model(s) found.' : 'No models found.';
            msRenderResults(fetched);
        } catch(e) {
            if (!_msCancelled) { document.getElementById('ms-status').textContent = 'Error: ' + e.message; document.getElementById('ms-results').innerHTML = '<p style="color:#f87171;padding:15px;">Failed to load.</p>'; }
        }
    }
}

function msFilter() {
    const q = document.getElementById('ms-filter-input').value.trim().toLowerCase();
    document.getElementById('ms-status').textContent = 'Searching…';
    const filtered = q ? _msAllItems.filter(m => (typeof m === 'string' ? m : m.id + ' ' + m.name).toLowerCase().includes(q)) : _msAllItems;
    document.getElementById('ms-status').textContent = filtered.length + ' result(s).';
    msRenderResults(filtered);
}

function msRenderResults(items) {
    _msDispItems = items;
    const el = document.getElementById('ms-results');
    if (!items || !items.length) { el.innerHTML = '<p style="color:#a0a0a0;text-align:center;padding:20px;">No results.</p>'; return; }
    el.innerHTML = items.map((item, i) => {
        const isStr = typeof item === 'string';
        const id = isStr ? item : item.id, label = isStr ? item : item.name;
        return `<div data-idx="${i}" onclick="msPickIdx(this)" style="padding:8px 12px;cursor:pointer;border-bottom:1px solid #0a2a50;font-size:13px;word-break:break-all;" onmouseover="this.style.background='#0f3460'" onmouseout="this.style.background=''">` +
               (id !== label ? `<span style="color:#c8d6e5;">${escHtml(id)}</span><span style="color:#888;font-size:11px;margin-left:6px;">${escHtml(label)}</span>` : `<span>${escHtml(id)}</span>`) + '</div>';
    }).join('');
}

function msPickIdx(el) {
    const i = parseInt(el.getAttribute('data-idx'));
    const item = _msDispItems[i]; const val = typeof item === 'string' ? item : item.id;
    if (_msCallback) _msCallback(val);
    msClose();
}

function msClose() {
    _msCancelled = true;
    const el = document.getElementById('ms-overlay'); if (el) el.style.display = 'none';
}

function msOpenAllForInput(btn) {
    const inputId = btn.getAttribute('data-input-id');
    const input = document.getElementById(inputId);
    msOpenAll(inputId, function(v) {
        if (input) { input.value = v; input.dispatchEvent(new Event('change')); }
    });
}

function buildModelSelectHtml(uid, currentValue, allModels, onChangeFn) {
    if (allModels.length <= 25) {
        const opts = allModels.map(m =>
            `<option value="${escHtml(m.id)}" ${currentValue === m.id ? 'selected' : ''}>${escHtml(m.name)}</option>`
        ).join('');
        return `<select id="${uid}" onchange="${onChangeFn}(this.value)" required>
            <option value="">Select model...</option>${opts}</select>`;
    } else {
        return `<div style="display:flex;gap:5px;align-items:center;">
            <input type="text" id="${escHtml(uid)}" value="${escHtml(currentValue)}"
                   onchange="${onChangeFn}(this.value)"
                   placeholder="Model ID…"
                   style="flex:1;padding:8px;border:1px solid #0f3460;border-radius:3px;background:#1a1a2e;color:#e0e0e0;font-size:14px;">
            <button type="button" class="btn btn-secondary"
                data-input-id="${escHtml(uid)}"
                onclick="msOpenAllForInput(this)"
                style="padding:7px 12px;white-space:nowrap;">Search</button>
        </div>`;
    }
}

const autoselectData = {
    config: {{ autoselect_json | safe }},
    rotations: {{ available_rotations | safe }},
    models: {{ available_models | safe }},
    saveUrl: "{{ url_for(request, '/dashboard/autoselect') }}",
    successUrl: "{{ url_for(request, '/dashboard/autoselect?success=1') }}"
};
let autoselectConfig = autoselectData.config;
let availableRotations = autoselectData.rotations;
let availableModels = autoselectData.models;
let expandedAutoselects = new Set();

function renderAutoselectList() {
    const container = document.getElementById('autoselect-list');
    container.innerHTML = '';
    
    if (!autoselectConfig || Object.keys(autoselectConfig).length === 0) {
        container.innerHTML = '<p style="color: #a0a0a0;">No autoselect configurations defined</p>';
        return;
    }
    
    Object.entries(autoselectConfig).forEach(([key, autoselect]) => {
        const autoselectItem = document.createElement('div');
        autoselectItem.className = 'autoselect-item';
        autoselectItem.style.cssText = 'border: 1px solid #0f3460; margin-bottom: 10px; border-radius: 5px; background: #1a1a2e;';
        
        const isExpanded = expandedAutoselects.has(key);
        const modelCount = autoselect.available_models ? autoselect.available_models.length : 0;
        const safeKey = key.replace(/\\/g, '\\\\').replace(/'/g, "\\'");

        autoselectItem.innerHTML = `
            <div class="autoselect-header" onclick="toggleAutoselect('${safeKey}')" style="padding: 15px; cursor: pointer; display: flex; justify-content: space-between; align-items: center; user-select: none;">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <span style="font-size: 18px;">${isExpanded ? '▼' : '▶'}</span>
                    <strong style="font-size: 16px;">${escHtml(autoselect.model_name || key)}</strong>
                    <span style="color: #a0a0a0; font-size: 14px;">(${modelCount} available model${modelCount !== 1 ? 's' : ''})</span>
                </div>
                <div style="display: flex; gap: 8px;">
                    <button type="button" class="btn btn-secondary" onclick="event.stopPropagation(); copyAutoselect('${safeKey}')" style="padding: 5px 15px;">Copy</button>
                    <button type="button" class="btn btn-secondary" onclick="event.stopPropagation(); removeAutoselect('${safeKey}')" style="background: #dc3545; padding: 5px 15px;">Remove</button>
                </div>
            </div>
            <div id="autoselect-details-${escHtmlAttr(key)}" style="display: ${isExpanded ? 'block' : 'none'}; padding: 20px; border-top: 1px solid #0f3460; background: #16213e;">
                <!-- Details will be rendered here -->
            </div>
        `;

        container.appendChild(autoselectItem);

        if (isExpanded) {
            renderAutoselectDetails(key);
        }
    });
}

function toggleAutoselect(key) {
    if (expandedAutoselects.has(key)) {
        expandedAutoselects.delete(key);
    } else {
        expandedAutoselects.add(key);
    }
    renderAutoselectList();
}

function renderAutoselectDetails(autoselectKey) {
    const container = document.getElementById(`autoselect-details-${autoselectKey}`);
    const autoselect = autoselectConfig[autoselectKey];
    const safeAKey = autoselectKey.replace(/\\/g, '\\\\').replace(/'/g, "\\'");

    // Default to "internal" if selection_model is not set
    const selectionValue = autoselect.selection_model || 'internal';
    
    // Build selection model options: internal + rotations + provider models
    let selectionOptions = `<option value="internal" ${selectionValue === 'internal' ? 'selected' : ''}>internal (Use configured internal model)</option>`;
    selectionOptions += '<optgroup label="Rotations">';
    selectionOptions += availableRotations.map(r =>
        `<option value="${r}" ${selectionValue === r ? 'selected' : ''}>${r}</option>`
    ).join('');
    selectionOptions += '</optgroup>';
    selectionOptions += '<optgroup label="Provider Models">';
    selectionOptions += availableModels.map(m =>
        `<option value="${m.id}" ${selectionValue === m.id ? 'selected' : ''}>${m.name}</option>`
    ).join('');
    selectionOptions += '</optgroup>';
    
    // Build fallback options: rotations + provider models
    let fallbackOptions = '<optgroup label="Rotations">';
    fallbackOptions += availableRotations.map(r =>
        `<option value="${r}" ${autoselect.fallback === r ? 'selected' : ''}>${r}</option>`
    ).join('');
    fallbackOptions += '</optgroup>';
    fallbackOptions += '<optgroup label="Provider Models">';
    fallbackOptions += availableModels.map(m =>
        `<option value="${m.id}" ${autoselect.fallback === m.id ? 'selected' : ''}>${m.name}</option>`
    ).join('');
    fallbackOptions += '</optgroup>';
    
    container.innerHTML = `
        <div class="form-group">
            <label>Model Name</label>
            <input type="text" value="${escHtml(autoselect.model_name)}" onchange="updateAutoselect('${escHtml(autoselectKey)}', 'model_name', this.value)" required>
        </div>

        <div class="form-group">
            <label>Capabilities (comma-separated)</label>
            <input type="text" value="${escHtml(autoselect.capabilities ? autoselect.capabilities.join(', ') : '')}" onchange="updateAutoselectCapabilities('${escHtml(autoselectKey)}', this.value)" placeholder="e.g., t2t, reasoning, multimodal">
        </div>
        
        <div class="form-group">
            <label>
                <input type="checkbox" ${autoselect.nsfw ? 'checked' : ''} onchange="updateAutoselect('${autoselectKey}', 'nsfw', this.checked)">
                NSFW
            </label>
        </div>
        
        <div class="form-group">
            <label>
                <input type="checkbox" ${autoselect.privacy ? 'checked' : ''} onchange="updateAutoselect('${autoselectKey}', 'privacy', this.checked)">
                Privacy
            </label>
        </div>
        
        <div class="form-group">
            <label>
                <input type="checkbox" ${autoselect.classify_nsfw ? 'checked' : ''} onchange="updateAutoselect('${autoselectKey}', 'classify_nsfw', this.checked)">
                Classify NSFW
            </label>
            <small style="color: #a0a0a0; font-size: 12px; display: block; margin-top: 5px;">Override global classify_nsfw setting for this autoselection</small>
        </div>
        
        <div class="form-group">
            <label>
                <input type="checkbox" ${autoselect.classify_privacy ? 'checked' : ''} onchange="updateAutoselect('${autoselectKey}', 'classify_privacy', this.checked)">
                Classify Privacy
            </label>
            <small style="color: #a0a0a0; font-size: 12px; display: block; margin-top: 5px;">Override global classify_privacy setting for this autoselection</small>
        </div>
        
        <div class="form-group">
            <label>
                <input type="checkbox" ${autoselect.classify_semantic ? 'checked' : ''} onchange="updateAutoselect('${autoselectKey}', 'classify_semantic', this.checked)">
                Classify Semantic
            </label>
            <small style="color: #a0a0a0; font-size: 12px; display: block; margin-top: 5px;">Override global classify_semantic setting for this autoselection</small>
        </div>
        
        <div class="form-group">
            <label>Description</label>
            <textarea onchange="updateAutoselect('${autoselectKey}', 'description', this.value)" style="min-height: 60px;">${autoselect.description || ''}</textarea>
        </div>
        
        <div class="form-group">
            <label>Selection Model (Model to use for analysis)</label>
            <select onchange="updateAutoselect('${autoselectKey}', 'selection_model', this.value)" required>
                <option value="">Select model...</option>
                ${selectionOptions}
            </select>
            <small style="color: #a0a0a0; font-size: 12px; display: block; margin-top: 5px;">Choose "internal" to use the configured internal model, or select a rotation/provider model</small>
        </div>
        
        <div class="form-group">
            <label>Fallback Model (Default if selection fails)</label>
            <select onchange="updateAutoselect('${autoselectKey}', 'fallback', this.value)" required>
                <option value="">Select model...</option>
                ${fallbackOptions}
            </select>
            <small style="color: #a0a0a0; font-size: 12px; display: block; margin-top: 5px;">Choose from rotations or provider models</small>
        </div>
        
        <h4 style="margin-top: 20px; margin-bottom: 10px;">Default Settings</h4>
        <p style="color: #a0a0a0; font-size: 14px; margin-bottom: 10px;">Default values for models in this autoselect (optional - auto-derived from first model if not set)</p>
        
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
            <div class="form-group">
                <label>Default Rate Limit (seconds)</label>
                <input type="number" value="${autoselect.default_rate_limit || ''}" onchange="updateAutoselect('${autoselectKey}', 'default_rate_limit', this.value ? parseFloat(this.value) : null)" step="0.1" placeholder="Optional">
            </div>
            
            <div class="form-group">
                <label>Default Max Request Tokens</label>
                <input type="number" value="${autoselect.default_max_request_tokens || ''}" onchange="updateAutoselect('${autoselectKey}', 'default_max_request_tokens', this.value ? parseInt(this.value) : null)" placeholder="Optional">
            </div>
            
            <div class="form-group">
                <label>Default Context Size</label>
                <input type="number" value="${autoselect.default_context_size || ''}" onchange="updateAutoselect('${autoselectKey}', 'default_context_size', this.value ? parseInt(this.value) : null)" placeholder="Optional">
            </div>
            
            <div class="form-group">
                <label>Default Rate Limit TPM</label>
                <input type="number" value="${autoselect.default_rate_limit_TPM || ''}" onchange="updateAutoselect('${autoselectKey}', 'default_rate_limit_TPM', this.value ? parseInt(this.value) : null)" placeholder="Optional">
                <small style="color: #a0a0a0; font-size: 12px; display: block; margin-top: 5px;">Tokens per minute limit</small>
            </div>
            
            <div class="form-group">
                <label>Default Rate Limit TPH</label>
                <input type="number" value="${autoselect.default_rate_limit_TPH || ''}" onchange="updateAutoselect('${autoselectKey}', 'default_rate_limit_TPH', this.value ? parseInt(this.value) : null)" placeholder="Optional">
                <small style="color: #a0a0a0; font-size: 12px; display: block; margin-top: 5px;">Tokens per hour limit</small>
            </div>
            
            <div class="form-group">
                <label>Default Rate Limit TPD</label>
                <input type="number" value="${autoselect.default_rate_limit_TPD || ''}" onchange="updateAutoselect('${autoselectKey}', 'default_rate_limit_TPD', this.value ? parseInt(this.value) : null)" placeholder="Optional">
                <small style="color: #a0a0a0; font-size: 12px; display: block; margin-top: 5px;">Tokens per day limit</small>
            </div>
            
            <div class="form-group">
                <label>Default Condense Context</label>
                <input type="number" value="${autoselect.default_condense_context || ''}" onchange="updateAutoselect('${autoselectKey}', 'default_condense_context', this.value ? parseInt(this.value) : null)" placeholder="Optional">
                <small style="color: #a0a0a0; font-size: 12px; display: block; margin-top: 5px;">Trigger context condensation at this token count</small>
            </div>
        </div>
        
        <h4 style="margin-top: 20px; margin-bottom: 10px;">Available Models</h4>
        <p style="color: #a0a0a0; font-size: 14px; margin-bottom: 10px;">Define which models can be selected and their descriptions for AI analysis</p>
        <div id="models-${autoselectKey}"></div>
        <button type="button" class="btn btn-secondary" onclick="addAutoselectModel('${safeAKey}')" style="margin-top: 10px;">Add Model</button>

        <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #0f3460; display: flex; gap: 10px; align-items: center;">
            <button type="button" class="btn" onclick="saveAutoselectItem('${safeAKey}')" style="background: #22c55e;">Save This Autoselect</button>
            <span id="asel-save-status-${autoselectKey}" style="font-size: 13px; color: #a0a0a0;"></span>
        </div>
    `;

    renderAutoselectModels(autoselectKey);
}

function renderAutoselectModels(autoselectKey) {
    const container = document.getElementById(`models-${autoselectKey}`);
    const autoselect = autoselectConfig[autoselectKey];
    
    if (!autoselect.available_models || autoselect.available_models.length === 0) {
        container.innerHTML = '<p style="color: #a0a0a0;">No models configured</p>';
        return;
    }
    
    container.innerHTML = '';
    autoselect.available_models.forEach((model, index) => {
        const modelDiv = document.createElement('div');
        modelDiv.style.cssText = 'border: 1px solid #0f3460; padding: 15px; margin-bottom: 10px; border-radius: 3px; background: #1a1a2e;';
        const safeKey = autoselectKey.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
        const allOptions = availableRotations.map(r => ({id: r, name: r})).concat(availableModels);
        const selUid = `asel-mod-${autoselectKey}-${index}`;

        modelDiv.innerHTML = `
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                <strong>Model ${index + 1}</strong>
                <button type="button" class="btn btn-secondary" onclick="removeAutoselectModel('${safeKey}', ${index})" style="background: #dc3545; padding: 5px 10px; font-size: 12px;">Remove</button>
            </div>

            <div class="form-group">
                <label>Model ID (Rotation or Provider Model)</label>
                ${buildModelSelectHtml(selUid, model.model_id || '', allOptions,
                    `function(v){updateAutoselectModel('${safeKey}',${index},'model_id',v)}`)}
                <small style="color: #a0a0a0; font-size: 12px; display: block; margin-top: 5px;">Choose from rotations or provider models</small>
            </div>
            
            <div class="form-group">
                <label>Description (Used by AI to select appropriate model)</label>
                <textarea onchange="updateAutoselectModel('${autoselectKey}', ${index}, 'description', this.value)" style="min-height: 80px;" required>${model.description || ''}</textarea>
                <small style="color: #666; font-size: 12px;">Be specific about when this model should be used (e.g., "Best for programming, code generation, debugging")</small>
            </div>
            
            <div class="form-group">
                <label>
                    <input type="checkbox" ${model.nsfw ? 'checked' : ''} onchange="updateAutoselectModel('${autoselectKey}', ${index}, 'nsfw', this.checked)">
                    NSFW
                </label>
            </div>
            
            <div class="form-group">
                <label>
                    <input type="checkbox" ${model.privacy ? 'checked' : ''} onchange="updateAutoselectModel('${autoselectKey}', ${index}, 'privacy', this.checked)">
                    Privacy
                </label>
            </div>
        `;
        
        container.appendChild(modelDiv);
    });
}

async function saveAutoselectItem(key) {
    const statusEl = document.getElementById(`asel-save-status-${key}`);
    if (statusEl) statusEl.textContent = 'Saving…';
    try {
        const result = await apiCall('POST', '/dashboard/api/autoselect', {
            autoselect_id: key,
            config: autoselectConfig[key]
        });
        if (result.success) {
            if (statusEl) { statusEl.textContent = 'Saved!'; statusEl.style.color = '#4ade80'; setTimeout(() => { statusEl.textContent = ''; }, 3000); }
        } else {
            if (statusEl) { statusEl.textContent = 'Error: ' + (result.error || 'Unknown'); statusEl.style.color = '#f87171'; }
        }
    } catch (e) {
        if (statusEl) { statusEl.textContent = 'Error: ' + e.message; statusEl.style.color = '#f87171'; }
    }
}

async function copyAutoselect(sourceKey) {
    const newKey = await showPrompt(`Copy "${sourceKey}" — enter new autoselect key:`, `${sourceKey}_copy`, 'autoselect-key', 'Copy Autoselect');
    if (!newKey) return;
    if (newKey === sourceKey) { showAlert('New key must be different from the source.', 'Invalid Key', '⚠️', 'warn'); return; }
    if (autoselectConfig[newKey]) { showAlert('Autoselect key already exists.', 'Duplicate Key', '⚠️', 'warn'); return; }
    const cloned = JSON.parse(JSON.stringify(autoselectConfig[sourceKey]));
    autoselectConfig[newKey] = cloned;
    try {
        const result = await apiCall('POST', '/dashboard/api/autoselect', { autoselect_id: newKey, config: cloned });
        if (!result.success) {
            showAlert('Error copying autoselect: ' + (result.error || 'Unknown'), 'Error', '❌', 'danger');
            delete autoselectConfig[newKey];
            return;
        }
    } catch (e) {
        showAlert('Error copying autoselect: ' + e.message, 'Error', '❌', 'danger');
        delete autoselectConfig[newKey];
        return;
    }
    expandedAutoselects.add(newKey);
    renderAutoselectList();
}

async function addAutoselect() {
    const key = await showPrompt('Enter autoselect key (e.g., "autoselect", "smart-select"):', '', 'e.g. autoselect', 'Add Autoselect');
    if (!key) return;
    if (autoselectConfig[key]) {
        showAlert('Autoselect key already exists', 'Duplicate Key', '⚠️', 'warn');
        return;
    }
    const newCfg = { model_name: key, description: '', selection_model: '', fallback: '', available_models: [] };
    autoselectConfig[key] = newCfg;
    try {
        const result = await apiCall('POST', '/dashboard/api/autoselect', { autoselect_id: key, config: newCfg });
        if (!result.success) {
            showAlert('Error creating autoselect: ' + (result.error || 'Unknown'), 'Error', '❌', 'danger');
            delete autoselectConfig[key];
            return;
        }
    } catch (e) {
        showAlert('Error creating autoselect: ' + e.message, 'Error', '❌', 'danger');
        delete autoselectConfig[key];
        return;
    }
    expandedAutoselects.add(key);
    renderAutoselectList();
}

async function removeAutoselect(key) {
    if (await showDangerConfirm(`Remove autoselect "${key}"?`, 'Remove Autoselect')) {
        try {
            const result = await apiCall('DELETE', '/dashboard/api/autoselect/' + encodeURIComponent(key));
            if (!result.success) { showAlert('Error: ' + (result.error || 'Unknown'), 'Error', '❌', 'danger'); return; }
        } catch (e) { showAlert('Error: ' + e.message, 'Error', '❌', 'danger'); return; }
        delete autoselectConfig[key];
        expandedAutoselects.delete(key);
        renderAutoselectList();
    }
}

function updateAutoselect(key, field, value) {
    autoselectConfig[key][field] = value;
}

function updateAutoselectCapabilities(autoselectKey, value) {
    const trimmed = value.trim();
    if (!trimmed) {
        autoselectConfig[autoselectKey].capabilities = null;
        return;
    }
    
    // Split by comma and clean up
    autoselectConfig[autoselectKey].capabilities = 
        trimmed.split(',').map(s => s.trim()).filter(s => s);
}

function addAutoselectModel(autoselectKey) {
    if (!autoselectConfig[autoselectKey].available_models) {
        autoselectConfig[autoselectKey].available_models = [];
    }
    
    autoselectConfig[autoselectKey].available_models.push({
        model_id: '',
        description: ''
    });
    
    renderAutoselectModels(autoselectKey);
}

async function removeAutoselectModel(autoselectKey, index) {
    if (await showDangerConfirm('Remove this model?', 'Remove Model')) {
        autoselectConfig[autoselectKey].available_models.splice(index, 1);
        renderAutoselectModels(autoselectKey);
    }
}

function updateAutoselectModel(autoselectKey, index, field, value) {
    autoselectConfig[autoselectKey].available_models[index][field] = value;
}

async function saveAutoselect() {
    try {
        const response = await fetch(autoselectData.saveUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'config=' + encodeURIComponent(JSON.stringify(autoselectConfig, null, 2))
        });
        
        if (response.ok) {
            window.location.href = autoselectData.successUrl;
        } else {
            showAlert('Error saving configuration', 'Error', '❌', 'danger');
        }
    } catch (error) {
        showAlert('Error: ' + error.message, 'Error', '❌', 'danger');
    }
}

// Initial render
renderAutoselectList();
</script>

<style>
.autoselect-item {
    animation: fadeIn 0.3s;
}

.autoselect-header:hover {
    background: #0f3460;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}

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

.form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: 500;
}

.form-group input[type="text"],
.form-group textarea,
.form-group select {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 3px;
    font-size: 14px;
}

.form-group input[type="checkbox"] {
    margin-right: 5px;
}
</style>
{% endblock %}
