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

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

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

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

<div class="form-group" style="margin-bottom: 20px;">
    <label>
        <input type="checkbox" id="global-notify" onchange="updateGlobalNotify(this.checked)">
        Global Notify Errors — return errors as messages (not HTTP 503) when all providers fail
    </label>
</div>

<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:var(--bg-page);border:1px solid var(--color-border);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:var(--color-text);"></h3>
          <button type="button" onclick="msClose()" style="background:none;border:none;color:var(--color-muted);cursor:pointer;font-size:22px;padding:0 4px;">&times;</button>
        </div>
        <div id="ms-status" style="font-size:13px;color:var(--color-muted);min-height:18px;margin-bottom:10px;"></div>
        <div style="display:flex;gap:8px;margin-bottom:12px;">
          <input type="text" id="ms-filter-input" placeholder="${window.i18n.t('rotations.filter_results')}"
            style="flex:1;padding:8px;border:1px solid var(--color-border);border-radius:3px;background:var(--bg-panel);color:var(--color-text);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;">${window.i18n.t('rotations.filter')}</button>
        </div>
        <div id="ms-results" style="overflow-y:auto;flex:1;max-height:340px;border:1px solid var(--color-border);border-radius:3px;background:var(--bg-panel);min-height:40px;"></div>
        <div style="margin-top:14px;display:flex;justify-content:flex-end;">
          <button type="button" onclick="msClose()" class="btn btn-secondary">${window.i18n.t('rotations.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 = window.i18n.t('rotations.checking_models');
    document.getElementById('ms-results').innerHTML = '<p style="color:var(--color-muted);text-align:center;padding:20px;">' + window.i18n.t('rotations.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 = window.i18n.t('rotations.fetching_from_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. ' + window.i18n.t('rotations.models_found_filter') : window.i18n.t('rotations.no_models_found');
        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;">' + window.i18n.t('rotations.failed_load') + '</p>'; }
    }
}

function msFilter() {
    const q = document.getElementById('ms-filter-input').value.trim().toLowerCase();
    document.getElementById('ms-status').textContent = window.i18n.t('rotations.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:var(--color-muted);text-align:center;padding:20px;">' + window.i18n.t('rotations.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 var(--color-border);font-size:13px;word-break:break-all;" onmouseover="this.style.background='var(--bg-accent)'" onmouseout="this.style.background=''">` +
               (id !== label ? `<span style="color:var(--color-text);">${escHtmlAttr(id)}</span><span style="color:var(--color-subtle);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')); }
    });
}

// Provider select widget: <select> for ≤25, datalist input for >25
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="">${window.i18n.t('rotations.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="${window.i18n.t('rotations.type_search_provider')}"
                   oninput="handleProviderInput('${uid}', this.value, ${onChangeFn})"
                   onchange="handleProviderInput('${uid}', this.value, ${onChangeFn})"
                   style="width:100%;padding:8px;border:1px solid var(--color-border);border-radius:3px;background:var(--bg-page);color:var(--color-text);font-size:14px;">
            <datalist id="${uid}-dl">${dlOpts}</datalist>
        </div>`;
    }
}

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

document.getElementById('global-notify').checked = rotationsConfig.notifyerrors || false;

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 var(--color-border); margin-bottom: 10px; border-radius: 5px; background: var(--bg-page);';
        
        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: var(--color-muted); font-size: 14px;">(${providerCount} ${window.i18n.t(providerCount !== 1 ? 'rotations.providers_plural' : 'rotations.providers_singular')})</span>
                </div>
                <div style="display: flex; gap: 8px;">
                    <button type="button" class="btn btn-secondary" onclick="event.stopPropagation(); copyRotation('${safeKey}')" style="padding: 5px 15px;">${window.i18n.t('rotations.copy')}</button>
                    <button type="button" class="btn btn-secondary" onclick="event.stopPropagation(); removeRotation('${safeKey}')" style="background: #dc3545; padding: 5px 15px;">${window.i18n.t('rotations.remove')}</button>
                </div>
            </div>
            <div id="rotation-details-${escHtmlAttr(key)}" style="display: ${isExpanded ? 'block' : 'none'}; padding: 20px; border-top: 1px solid var(--color-border); background: var(--bg-panel);">
            </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>${window.i18n.t('rotations.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)">
                ${window.i18n.t('rotations.notify_errors')} — ${window.i18n.t('rotations.notify_errors_desc')}
            </label>
        </div>
        
        <div class="form-group">
            <label>${window.i18n.t('rotations.capabilities')}</label>
            <input type="text" value="${rotation.capabilities ? rotation.capabilities.join(', ') : ''}" onchange="updateRotationCapabilities('${rotationKey}', this.value)" placeholder="${window.i18n.t('rotations.capabilities_placeholder')}">
        </div>
        
        <div class="form-group">
            <label>${window.i18n.t('rotations.default_rate_limit')}</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="${window.i18n.t('rotations.optional')}">
        </div>
        
        <div class="form-group">
            <label>${window.i18n.t('rotations.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="${window.i18n.t('rotations.optional')}">
        </div>
        
        <div class="form-group">
            <label>
                <input type="checkbox" ${rotation.nsfw ? 'checked' : ''} onchange="updateRotation('${rotationKey}', 'nsfw', this.checked)">
                ${window.i18n.t('rotations.nsfw')}
            </label>
        </div>
        
        <div class="form-group">
            <label>
                <input type="checkbox" ${rotation.privacy ? 'checked' : ''} onchange="updateRotation('${rotationKey}', 'privacy', this.checked)">
                ${window.i18n.t('rotations.privacy')}
            </label>
        </div>
        
        <h4 style="margin-top: 20px; margin-bottom: 10px;">${window.i18n.t('rotations.providers_section')}</h4>
        <div id="providers-${rotationKey}"></div>
        <button type="button" class="btn btn-secondary" onclick="addRotationProvider('${safeRKey}')" style="margin-top: 10px;">${window.i18n.t('rotations.add_provider')}</button>

        <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid var(--color-border); display: flex; gap: 10px; align-items: center;">
            <button type="button" class="btn" onclick="saveRotation('${safeRKey}')" style="background: #22c55e;">${window.i18n.t('rotations.save_this')}</button>
            <span id="rot-save-status-${rotationKey}" style="font-size: 13px; color: var(--color-muted);"></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: var(--color-muted);">' + window.i18n.t('rotations.no_providers') + '</p>';
        return;
    }
    
    container.innerHTML = '';
    rotation.providers.forEach((provider, providerIndex) => {
        const providerDiv = document.createElement('div');
        providerDiv.style.cssText = 'border: 1px solid var(--color-border); padding: 15px; margin-bottom: 10px; border-radius: 3px; background: var(--bg-page);';
        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>${window.i18n.t('rotations.provider_label')} ${providerIndex + 1}</strong>
                <button type="button" class="btn btn-secondary" onclick="removeRotationProvider('${safeKey}', ${providerIndex})" style="background: #dc3545; padding: 5px 10px; font-size: 12px;">${window.i18n.t('rotations.remove')}</button>
            </div>

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

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

            <h5 style="margin-top: 15px; margin-bottom: 10px;">${window.i18n.t('rotations.models_section')}</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;">${window.i18n.t('rotations.add_model')}</button>
            <p style="font-size: 12px; color: var(--color-muted); margin-top: 5px;">${window.i18n.t('rotations.leave_empty')}</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: var(--color-muted); font-size: 12px;">' + window.i18n.t('rotations.no_models') + '</p>';
        return;
    }

    container.innerHTML = '';
    provider.models.forEach((model, modelIndex) => {
        const modelDiv = document.createElement('div');
        modelDiv.style.cssText = 'border: 1px solid var(--color-border); padding: 10px; margin-bottom: 8px; border-radius: 3px; background: var(--bg-panel);';
        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;">${window.i18n.t('rotations.model_label')} ${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;">${window.i18n.t('rotations.remove')}</button>
            </div>

            <div class="form-group" style="margin-bottom: 8px;">
                <label style="font-size: 12px;">${window.i18n.t('rotations.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;">${window.i18n.t('rotations.search')}</button>
                </div>
            </div>
            
            <div class="form-group" style="margin-bottom: 8px;">
                <label style="font-size: 12px;">${window.i18n.t('rotations.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;">${window.i18n.t('rotations.rate_limit')}</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;">${window.i18n.t('rotations.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="${window.i18n.t('rotations.optional')}" style="font-size: 12px; padding: 5px;">
            </div>
            
            <div class="form-group" style="margin-bottom: 8px;">
                <label style="font-size: 12px;">${window.i18n.t('rotations.context_size')}</label>
                <input type="number" value="${model.context_size || ''}" onchange="updateRotationModel('${rotationKey}', ${providerIndex}, ${modelIndex}, 'context_size', this.value ? parseInt(this.value) : null)" placeholder="${window.i18n.t('rotations.optional')}" style="font-size: 12px; padding: 5px;">
            </div>
            
            <div class="form-group" style="margin-bottom: 8px;">
                <label style="font-size: 12px;">${window.i18n.t('rotations.condense_context_pct')}</label>
                <input type="number" value="${model.condense_context || ''}" onchange="updateRotationModel('${rotationKey}', ${providerIndex}, ${modelIndex}, 'condense_context', this.value ? parseInt(this.value) : null)" placeholder="${window.i18n.t('rotations.optional')} (default: 80)" style="font-size: 12px; padding: 5px;">
            </div>
            
            <div class="form-group" style="margin-bottom: 0;">
                <label style="font-size: 12px;">${window.i18n.t('rotations.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="${window.i18n.t('rotations.condense_method_placeholder')}" style="font-size: 12px; padding: 5px;">
            </div>
        `;
        
        container.appendChild(modelDiv);
    });
}

function updateGlobalNotify(value) {
    rotationsConfig.notifyerrors = value;
}

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 = window.i18n.t('rotations.saving');
    try {
        const result = await apiCall('POST', '/dashboard/api/rotation', {
            rotation_id: key,
            config: rotationsConfig.rotations[key]
        });
        if (result.success) {
            if (statusEl) { statusEl.textContent = window.i18n.t('rotations.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 — defer until i18n is ready so translated strings are available
function _doInitialRender() { renderRotationsList(); }
if (window.i18n) { _doInitialRender(); } else { document.addEventListener('i18n:ready', _doInitialRender, {once: true}); }
</script>

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

.rotation-header:hover {
    background: var(--bg-accent);
}

@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: var(--color-text);
}

.form-group input[type="text"],
.form-group input[type="number"],
.form-group select {
    width: 100%;
    padding: 8px;
    border: 1px solid var(--color-border);
    border-radius: 3px;
    font-size: 14px;
    background: var(--bg-page);
    color: var(--color-text);
}

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