<!--
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 Rotations - AISBF{% endblock %}

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

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

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

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

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

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

const rotationsData = {
    config: {{ rotations_json | safe }},
    providers: {{ available_providers | safe }},
    saveUrl: "{{ url_for(request, '/dashboard/rotations') }}",
    successUrl: "{{ url_for(request, '/dashboard/rotations?success=1') }}"
};
let rotationsConfig = rotationsData.config;
let availableProviders = rotationsData.providers;
let expandedRotations = new Set();

// ===== 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 msOpenProvider(providerId, 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 — ' + providerId;
    document.getElementById('ms-filter-input').value = '';
    document.getElementById('ms-status').textContent = 'Checking provider models…';
    document.getElementById('ms-results').innerHTML = '<p style="color:#a0a0a0;text-align:center;padding:20px;">Loading…</p>';
    try {
        let r = await fetch('/dashboard/providers/' + encodeURIComponent(providerId) + '/configured-models');
        if (_msCancelled) return;
        let d = await r.json(); let m = d.models || [];
        if (!m.length) {
            document.getElementById('ms-status').textContent = 'No local model list — fetching from provider API…';
            r = await fetch('/dashboard/providers/' + encodeURIComponent(providerId) + '/search-models?refresh=true');
            if (_msCancelled) return;
            d = await r.json(); m = d.models || [];
        }
        if (_msCancelled) return;
        _msAllItems = m;
        document.getElementById('ms-status').textContent = m.length ? m.length + ' model(s) found. Use Filter to narrow results.' : 'No models found for this provider.';
        msRenderResults(m);
    } 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 models.</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;">${escHtmlAttr(id)}</span><span style="color:#888;font-size:11px;margin-left:6px;">${escHtmlAttr(label)}</span>` : `<span>${escHtmlAttr(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 msOpenProviderForInput(btn) {
    const providerId = btn.getAttribute('data-provider');
    const inputId = btn.getAttribute('data-input-id');
    const input = document.getElementById(inputId);
    msOpenProvider(providerId, inputId, function(v) {
        if (input) { input.value = v; input.dispatchEvent(new Event('change')); }
    });
}

function buildProviderSelectHtml(uid, currentValue, onChangeFn) {
    if (availableProviders.length <= 25) {
        const opts = availableProviders.map(p =>
            `<option value="${escHtmlAttr(p)}" ${currentValue === p ? 'selected' : ''}>${escHtmlAttr(p)}</option>`
        ).join('');
        return `<select id="${uid}" onchange="${onChangeFn}(this.value)" required>
            <option value="">Select provider...</option>${opts}</select>`;
    } else {
        const dlOpts = availableProviders.map(p => `<option value="${escHtmlAttr(p)}">`).join('');
        return `<div style="position:relative;">
            <input type="text" id="${uid}" value="${escHtmlAttr(currentValue)}" list="${uid}-dl"
                   placeholder="Type to search provider..."
                   oninput="handleProviderInput('${uid}',this.value,${onChangeFn})"
                   onchange="handleProviderInput('${uid}',this.value,${onChangeFn})"
                   style="width:100%;padding:8px;border:1px solid #0f3460;border-radius:3px;background:#1a1a2e;color:#e0e0e0;font-size:14px;">
            <datalist id="${uid}-dl">${dlOpts}</datalist>
        </div>`;
    }
}

function handleProviderInput(uid, value, callback) {
    if (availableProviders.includes(value) || value === '') {
        callback(value);
    }
}

function renderRotationsList() {
    const container = document.getElementById('rotations-list');
    container.innerHTML = '';
    
    Object.entries(rotationsConfig.rotations || {}).forEach(([key, rotation]) => {
        const rotationItem = document.createElement('div');
        rotationItem.className = 'rotation-item';
        rotationItem.style.cssText = 'border: 1px solid #0f3460; margin-bottom: 10px; border-radius: 5px; background: #1a1a2e;';
        
        const isExpanded = expandedRotations.has(key);
        const providerCount = rotation.providers ? rotation.providers.length : 0;
        const safeKey = key.replace(/\\/g, '\\\\').replace(/'/g, "\\'");

        rotationItem.innerHTML = `
            <div class="rotation-header" onclick="toggleRotation('${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;">${escHtmlAttr(key)}</strong>
                    <span style="color: #a0a0a0; font-size: 14px;">(${providerCount} provider${providerCount !== 1 ? 's' : ''})</span>
                </div>
                <div style="display: flex; gap: 8px;">
                    <button type="button" class="btn btn-secondary" onclick="event.stopPropagation(); copyRotation('${safeKey}')" style="padding: 5px 15px;">Copy</button>
                    <button type="button" class="btn btn-secondary" onclick="event.stopPropagation(); removeRotation('${safeKey}')" style="background: #dc3545; padding: 5px 15px;">Remove</button>
                </div>
            </div>
            <div id="rotation-details-${escHtmlAttr(key)}" style="display: ${isExpanded ? 'block' : 'none'}; padding: 20px; border-top: 1px solid #0f3460; background: #16213e;">
            </div>
        `;

        container.appendChild(rotationItem);

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

function toggleRotation(key) {
    if (expandedRotations.has(key)) {
        expandedRotations.delete(key);
    } else {
        expandedRotations.add(key);
    }
    renderRotationsList();
}

function renderRotationDetails(rotationKey) {
    const container = document.getElementById(`rotation-details-${rotationKey}`);
    const rotation = rotationsConfig.rotations[rotationKey];
    const safeRKey = rotationKey.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
    
    container.innerHTML = `
        <div class="form-group">
            <label>Model Name</label>
            <input type="text" value="${rotation.model_name}" onchange="updateRotation('${rotationKey}', 'model_name', this.value)" required>
        </div>
        
        <div class="form-group">
            <label>
                <input type="checkbox" ${rotation.notifyerrors ? 'checked' : ''} onchange="updateRotation('${rotationKey}', 'notifyerrors', this.checked)">
                Notify Errors
            </label>
            <small style="color: #888; font-size: 12px; display: block;">
                When enabled, provider errors will be returned to the client instead of silently failing over to next provider.
                Disable this for silent failover without exposing internal errors.
            </small>
        </div>
        
        <div class="form-group">
            <label>Capabilities (comma-separated)</label>
            <input type="text" value="${rotation.capabilities ? rotation.capabilities.join(', ') : ''}" onchange="updateRotationCapabilities('${rotationKey}', this.value)" placeholder="e.g., code_generation, t2t, reasoning">
        </div>
        
        <div class="form-group">
            <label>Default Rate Limit (seconds)</label>
            <input type="number" value="${rotation.default_rate_limit || ''}" onchange="updateRotation('${rotationKey}', 'default_rate_limit', this.value ? parseFloat(this.value) : null)" step="0.1" placeholder="Optional">
        </div>
        
        <div class="form-group">
            <label>Default Context Size</label>
            <input type="number" value="${rotation.default_context_size || ''}" onchange="updateRotation('${rotationKey}', 'default_context_size', this.value ? parseInt(this.value) : null)" placeholder="Optional">
        </div>
        
        <div class="form-group">
            <label>
                <input type="checkbox" ${rotation.nsfw ? 'checked' : ''} onchange="updateRotation('${rotationKey}', 'nsfw', this.checked)">
                NSFW
            </label>
        </div>
        
        <div class="form-group">
            <label>
                <input type="checkbox" ${rotation.privacy ? 'checked' : ''} onchange="updateRotation('${rotationKey}', 'privacy', this.checked)">
                Privacy
            </label>
        </div>
        
        <h4 style="margin-top: 20px; margin-bottom: 10px;">Providers</h4>
        <div id="providers-${rotationKey}"></div>
        <button type="button" class="btn btn-secondary" onclick="addRotationProvider('${safeRKey}')" style="margin-top: 10px;">Add Provider</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="saveRotation('${safeRKey}')" style="background: #22c55e;">Save This Rotation</button>
            <span id="rot-save-status-${rotationKey}" style="font-size: 13px; color: #a0a0a0;"></span>
        </div>
    `;

    renderRotationProviders(rotationKey);
}

function renderRotationProviders(rotationKey) {
    const container = document.getElementById(`providers-${rotationKey}`);
    const rotation = rotationsConfig.rotations[rotationKey];
    
    if (!rotation.providers || rotation.providers.length === 0) {
        container.innerHTML = '<p style="color: #a0a0a0;">No providers configured</p>';
        return;
    }
    
    container.innerHTML = '';
    rotation.providers.forEach((provider, providerIndex) => {
        const providerDiv = document.createElement('div');
        providerDiv.style.cssText = 'border: 1px solid #0f3460; padding: 15px; margin-bottom: 10px; border-radius: 3px; background: #1a1a2e;';
        const safeKey = rotationKey.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
        const provSelUid = `prov-sel-${rotationKey}-${providerIndex}`;

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

            <div class="form-group">
                <label>Provider ID</label>
                ${buildProviderSelectHtml(provSelUid, provider.provider_id || '',
                    `function(v){updateRotationProvider('${safeKey}',${providerIndex},'provider_id',v)}`)}
            </div>

            <div class="form-group">
                <label>Weight (optional, for provider-level weight)</label>
                <input type="number" value="${provider.weight || ''}" onchange="updateRotationProvider('${safeKey}', ${providerIndex}, 'weight', this.value ? parseInt(this.value) : null)" placeholder="Optional">
            </div>

            <h5 style="margin-top: 15px; margin-bottom: 10px;">Models</h5>
            <div id="models-${rotationKey}-${providerIndex}"></div>
            <button type="button" class="btn btn-secondary" onclick="addRotationModel('${safeKey}', ${providerIndex})" style="margin-top: 10px; font-size: 12px;">Add Model</button>
            <p style="font-size: 12px; color: #a0a0a0; margin-top: 5px;">Leave models empty to use all models from provider config</p>
        `;

        container.appendChild(providerDiv);
        renderRotationModels(rotationKey, providerIndex);
    });
}

function renderRotationModels(rotationKey, providerIndex) {
    const container = document.getElementById(`models-${rotationKey}-${providerIndex}`);
    const provider = rotationsConfig.rotations[rotationKey].providers[providerIndex];

    if (!provider.models || provider.models.length === 0) {
        container.innerHTML = '<p style="color: #a0a0a0; font-size: 12px;">No models specified (will use all from provider)</p>';
        return;
    }

    container.innerHTML = '';
    provider.models.forEach((model, modelIndex) => {
        const modelDiv = document.createElement('div');
        modelDiv.style.cssText = 'border: 1px solid #0f3460; padding: 10px; margin-bottom: 8px; border-radius: 3px; background: #16213e;';
        const safeKey = rotationKey.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
        const inputId = `mdl-inp-${rotationKey}-${providerIndex}-${modelIndex}`;
        const providerId = provider.provider_id || '';

        modelDiv.innerHTML = `
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                <strong style="font-size: 13px;">Model ${modelIndex + 1}</strong>
                <button type="button" onclick="removeRotationModel('${safeKey}', ${providerIndex}, ${modelIndex})" style="background: #dc3545; color: white; border: none; padding: 3px 8px; border-radius: 3px; cursor: pointer; font-size: 11px;">Remove</button>
            </div>

            <div class="form-group" style="margin-bottom: 8px;">
                <label style="font-size: 12px;">Model Name</label>
                <div style="display:flex;gap:5px;align-items:center;">
                    <input type="text" id="${escHtmlAttr(inputId)}" value="${escHtmlAttr(model.name)}"
                        oninput="updateRotationModel('${safeKey}',${providerIndex},${modelIndex},'name',this.value)"
                        onchange="updateRotationModel('${safeKey}',${providerIndex},${modelIndex},'name',this.value)"
                        placeholder="Model name…"
                        required style="flex:1;font-size:12px;padding:5px;">
                    <button type="button" class="btn btn-secondary"
                        data-provider="${escHtmlAttr(providerId)}"
                        data-input-id="${escHtmlAttr(inputId)}"
                        onclick="msOpenProviderForInput(this)"
                        style="padding:4px 8px;font-size:11px;white-space:nowrap;">Search</button>
                </div>
            </div>
            
            <div class="form-group" style="margin-bottom: 8px;">
                <label style="font-size: 12px;">Weight</label>
                <input type="number" value="${model.weight || 1}" onchange="updateRotationModel('${rotationKey}', ${providerIndex}, ${modelIndex}, 'weight', parseInt(this.value))" style="font-size: 12px; padding: 5px;">
            </div>
            
            <div class="form-group" style="margin-bottom: 8px;">
                <label style="font-size: 12px;">Rate Limit (seconds)</label>
                <input type="number" value="${model.rate_limit || 0}" onchange="updateRotationModel('${rotationKey}', ${providerIndex}, ${modelIndex}, 'rate_limit', parseFloat(this.value))" step="0.1" style="font-size: 12px; padding: 5px;">
            </div>
            
            <div class="form-group" style="margin-bottom: 8px;">
                <label style="font-size: 12px;">Max Request Tokens</label>
                <input type="number" value="${model.max_request_tokens || ''}" onchange="updateRotationModel('${rotationKey}', ${providerIndex}, ${modelIndex}, 'max_request_tokens', this.value ? parseInt(this.value) : null)" placeholder="Optional" style="font-size: 12px; padding: 5px;">
            </div>
            
            <div class="form-group" style="margin-bottom: 8px;">
                <label style="font-size: 12px;">Context Size</label>
                <input type="number" value="${model.context_size || ''}" onchange="updateRotationModel('${rotationKey}', ${providerIndex}, ${modelIndex}, 'context_size', this.value ? parseInt(this.value) : null)" placeholder="Optional" style="font-size: 12px; padding: 5px;">
            </div>
            
            <div class="form-group" style="margin-bottom: 8px;">
                <label style="font-size: 12px;">Condense Context (%)</label>
                <input type="number" value="${model.condense_context || ''}" onchange="updateRotationModel('${rotationKey}', ${providerIndex}, ${modelIndex}, 'condense_context', this.value ? parseInt(this.value) : null)" placeholder="Optional (default: 80)" style="font-size: 12px; padding: 5px;">
            </div>
            
            <div class="form-group" style="margin-bottom: 0;">
                <label style="font-size: 12px;">Condense Method</label>
                <input type="text" value="${Array.isArray(model.condense_method) ? model.condense_method.join(', ') : (model.condense_method || '')}" onchange="updateRotationModelCondenseMethod('${rotationKey}', ${providerIndex}, ${modelIndex}, this.value)" placeholder="e.g., semantic, conversational, hierarchical" style="font-size: 12px; padding: 5px;">
            </div>
        `;
        
        container.appendChild(modelDiv);
    });
}

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();
}

async function saveRotation(key) {
    const statusEl = document.getElementById(`rot-save-status-${key}`);
    if (statusEl) statusEl.textContent = 'Saving…';
    try {
        const result = await apiCall('POST', '/dashboard/api/rotation', {
            rotation_id: key,
            config: rotationsConfig.rotations[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 copyRotation(sourceKey) {
    const newKey = await showPrompt(`Copy "${sourceKey}" — enter new rotation key:`, `${sourceKey}_copy`, 'rotation-key', 'Copy Rotation');
    if (!newKey) return;
    if (newKey === sourceKey) { showAlert('New key must be different from the source.', 'Invalid Key', '⚠️', 'warn'); return; }
    if (rotationsConfig.rotations[newKey]) { showAlert('Rotation key already exists.', 'Duplicate Key', '⚠️', 'warn'); return; }
    const cloned = JSON.parse(JSON.stringify(rotationsConfig.rotations[sourceKey]));
    rotationsConfig.rotations[newKey] = cloned;
    try {
        const result = await apiCall('POST', '/dashboard/api/rotation', { rotation_id: newKey, config: cloned });
        if (!result.success) {
            showAlert('Error copying rotation: ' + (result.error || 'Unknown'), 'Error', '❌', 'danger');
            delete rotationsConfig.rotations[newKey];
            return;
        }
    } catch (e) {
        showAlert('Error copying rotation: ' + e.message, 'Error', '❌', 'danger');
        delete rotationsConfig.rotations[newKey];
        return;
    }
    expandedRotations.add(newKey);
    renderRotationsList();
}

async function addRotation() {
    const key = await showPrompt('Enter rotation key (e.g., "coding", "general"):', '', 'rotation-key', 'Add Rotation');
    if (!key) return;
    if (rotationsConfig.rotations[key]) {
        showAlert('Rotation key already exists', 'Duplicate Key', '⚠️', 'warn');
        return;
    }
    if (!rotationsConfig.rotations) rotationsConfig.rotations = {};
    const newCfg = { model_name: key, notifyerrors: false, capabilities: [], providers: [] };
    rotationsConfig.rotations[key] = newCfg;
    try {
        const result = await apiCall('POST', '/dashboard/api/rotation', { rotation_id: key, config: newCfg });
        if (!result.success) {
            showAlert('Error creating rotation: ' + (result.error || 'Unknown'), 'Error', '❌', 'danger');
            delete rotationsConfig.rotations[key];
            return;
        }
    } catch (e) {
        showAlert('Error creating rotation: ' + e.message, 'Error', '❌', 'danger');
        delete rotationsConfig.rotations[key];
        return;
    }
    expandedRotations.add(key);
    renderRotationsList();
}

async function removeRotation(key) {
    if (await showDangerConfirm(`Remove rotation "${key}"?`, 'Remove Rotation')) {
        try {
            const result = await apiCall('DELETE', '/dashboard/api/rotation/' + encodeURIComponent(key));
            if (!result.success) { showAlert('Error: ' + (result.error || 'Unknown'), 'Error', '❌', 'danger'); return; }
        } catch (e) { showAlert('Error: ' + e.message, 'Error', '❌', 'danger'); return; }
        delete rotationsConfig.rotations[key];
        expandedRotations.delete(key);
        renderRotationsList();
    }
}

function updateRotation(key, field, value) {
    rotationsConfig.rotations[key][field] = value;
}

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

function addRotationProvider(rotationKey) {
    if (!rotationsConfig.rotations[rotationKey].providers) {
        rotationsConfig.rotations[rotationKey].providers = [];
    }
    
    rotationsConfig.rotations[rotationKey].providers.push({
        provider_id: '',
        models: []
    });
    
    renderRotationProviders(rotationKey);
}

async function removeRotationProvider(rotationKey, providerIndex) {
    if (await showDangerConfirm('Remove this provider?', 'Remove Provider')) {
        rotationsConfig.rotations[rotationKey].providers.splice(providerIndex, 1);
        renderRotationProviders(rotationKey);
    }
}

function updateRotationProvider(rotationKey, providerIndex, field, value) {
    rotationsConfig.rotations[rotationKey].providers[providerIndex][field] = value;
}

function addRotationModel(rotationKey, providerIndex) {
    const provider = rotationsConfig.rotations[rotationKey].providers[providerIndex];
    if (!provider.models) {
        provider.models = [];
    }
    
    provider.models.push({
        name: '',
        weight: 1,
        rate_limit: 0
    });
    
    renderRotationModels(rotationKey, providerIndex);
}

async function removeRotationModel(rotationKey, providerIndex, modelIndex) {
    if (await showDangerConfirm('Remove this model?', 'Remove Model')) {
        rotationsConfig.rotations[rotationKey].providers[providerIndex].models.splice(modelIndex, 1);
        renderRotationModels(rotationKey, providerIndex);
    }
}

function updateRotationModel(rotationKey, providerIndex, modelIndex, field, value) {
    rotationsConfig.rotations[rotationKey].providers[providerIndex].models[modelIndex][field] = value;
}

function updateRotationModelCondenseMethod(rotationKey, providerIndex, modelIndex, value) {
    const trimmed = value.trim();
    if (!trimmed) {
        rotationsConfig.rotations[rotationKey].providers[providerIndex].models[modelIndex].condense_method = null;
        return;
    }
    
    // Check if it's a comma-separated list
    if (trimmed.includes(',')) {
        rotationsConfig.rotations[rotationKey].providers[providerIndex].models[modelIndex].condense_method = 
            trimmed.split(',').map(s => s.trim()).filter(s => s);
    } else {
        rotationsConfig.rotations[rotationKey].providers[providerIndex].models[modelIndex].condense_method = trimmed;
    }
}

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

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

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

.rotation-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;
    color: #e0e0e0;
}

.form-group input[type="text"],
.form-group input[type="number"],
.form-group select {
    width: 100%;
    padding: 8px;
    border: 1px solid #0f3460;
    border-radius: 3px;
    font-size: 14px;
    background: #1a1a2e;
    color: #e0e0e0;
}

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