/**
 * models.js — NAM Model Manager page.
 */

async function loadModels() {
    const listEl = document.getElementById('model-list');
    const currentEl = document.getElementById('current-model');

    listEl.innerHTML = '<p class="loading">Loading...</p>';

    try {
        const data = await apiGet('/models');
        renderModelList(listEl, currentEl, data);
    } catch (e) {
        listEl.innerHTML = `<p class="text-muted">Error: ${e.message}</p>`;
    }
}

function renderModelList(listEl, currentEl, data) {
    const currentName = data.current;

    // Current model display
    if (currentEl) {
        if (currentName) {
            currentEl.innerHTML = `<span class="model-name">${escapeHtml(currentName)}</span>`;
            document.getElementById('unload-model-btn').style.display = 'inline-flex';
        } else {
            currentEl.innerHTML = `<span class="model-name">None loaded</span>`;
            document.getElementById('unload-model-btn').style.display = 'none';
        }
    }

    // Available models
    if (!data.models || data.models.length === 0) {
        listEl.innerHTML = '<p class="text-muted">No .nam models found in the pedal directory.</p>';
        return;
    }

    let html = '';
    for (const m of data.models) {
        const isLoaded = m.name === currentName;
        html += `<div class="model-item ${isLoaded ? 'loaded' : ''}">`;
        html += `<div>
                    <div class="model-name">${escapeHtml(m.name)}</div>
                    <div class="model-meta">
                        ${m.architecture} · ${m.size_mb} MB
                        ${isLoaded ? '· <strong style="color:var(--success)">CURRENT</strong>' : ''}
                    </div>
                 </div>`;
        if (!isLoaded) {
            html += `<button class="btn btn-primary" onclick='loadModel(${JSON.stringify(m.path)})'
                             style="padding:4px 10px; font-size:0.78rem;">Load</button>`;
        }
        html += '</div>';
    }
    listEl.innerHTML = html;
}

async function loadModel(path) {
    try {
        await apiPost('/models/load', { path });
        loadModels();
    } catch (e) {
        alert('Failed to load model: ' + e.message);
    }
}

async function unloadModel() {
    try {
        await apiPost('/models/unload');
        loadModels();
    } catch (e) {
        alert('Failed to unload: ' + e.message);
    }
}

async function uploadModel() {
    const input = document.getElementById('model-upload-input');
    const file = input.files[0];
    if (!file) return alert('Select a .nam file first.');

    const formData = new FormData();
    formData.append('file', file);

    try {
        const res = await fetch('/api/models/upload', { method: 'POST', body: formData });
        if (!res.ok) throw new Error(`Upload failed: ${res.status}`);
        input.value = '';
        loadModels();
    } catch (e) {
        alert('Upload error: ' + e.message);
    }
}

document.addEventListener('DOMContentLoaded', loadModels);

// ── Tone3000 Browser ────────────────────────────────────────────────

const INSTALLED_MODELS_KEY = 'tonedownload_installed_models';

function getInstalledModels() {
    try {
        return JSON.parse(localStorage.getItem(INSTALLED_MODELS_KEY) || '[]');
    } catch { return []; }
}

function markInstalled(url) {
    const installed = getInstalledModels();
    if (!installed.includes(url)) {
        installed.push(url);
        localStorage.setItem(INSTALLED_MODELS_KEY, JSON.stringify(installed));
    }
}

function isInstalled(url) {
    return getInstalledModels().includes(url);
}

async function searchToneModels() {
    const input = document.getElementById('model-tone-search');
    const query = input.value.trim();
    const resultsEl = document.getElementById('model-tone-results');
    const loaderEl = document.getElementById('model-tone-loader');
    const offlineEl = document.getElementById('model-tone-offline');

    resultsEl.innerHTML = '';
    offlineEl.style.display = 'none';

    if (!query) {
        loadTrendingModels();
        return;
    }

    loaderEl.style.display = 'block';

    try {
        const data = await apiGet('/models/tonedownload/search?q=' + encodeURIComponent(query));
        loaderEl.style.display = 'none';
        renderToneResults(resultsEl, data.results || [], 'model');
    } catch (e) {
        loaderEl.style.display = 'none';
        if (e.message.includes('503') || e.message.includes('Failed to fetch')) {
            offlineEl.style.display = 'block';
        } else {
            resultsEl.innerHTML = `<p class="text-muted">Error: ${escapeHtml(e.message)}</p>`;
        }
    }
}

async function loadTrendingModels() {
    const resultsEl = document.getElementById('model-tone-results');
    const loaderEl = document.getElementById('model-tone-loader');
    const offlineEl = document.getElementById('model-tone-offline');

    resultsEl.innerHTML = '';
    offlineEl.style.display = 'none';
    loaderEl.style.display = 'block';

    try {
        const data = await apiGet('/models/tonedownload/search?q=');
        loaderEl.style.display = 'none';
        renderToneResults(resultsEl, data.results || [], 'model');
    } catch (e) {
        loaderEl.style.display = 'none';
        if (e.message.includes('503') || e.message.includes('Failed to fetch')) {
            offlineEl.style.display = 'block';
        } else {
            resultsEl.innerHTML = `<p class="text-muted">Error: ${escapeHtml(e.message)}</p>`;
        }
    }
}

function renderToneResults(container, results, type) {
    if (!results || results.length === 0) {
        container.innerHTML = '<p class="text-muted">No results found.</p>';
        return;
    }

    let html = '';
    for (const r of results) {
        const installed = isInstalled(r.download_url);
        const thumb = r.thumbnail
            ? `<img src="${escapeHtml(r.thumbnail)}" alt="" class="tonedownload-thumb" loading="lazy" onerror="this.style.display='none'">`
            : '<div class="tonedownload-thumb tonedownload-thumb-placeholder">🎸</div>';

        html += `<div class="tonedownload-card ${installed ? 'installed' : ''}">
            ${thumb}
            <div class="tonedownload-card-body">
                <div class="tonedownload-card-name">${escapeHtml(r.name)}</div>
                <div class="tonedownload-card-meta">
                    ${escapeHtml(r.author)} · ${escapeHtml(r.size_display)}
                    ${r.architecture ? ` · ${escapeHtml(r.architecture)}` : ''}
                </div>
                ${r.tone_description ? `<div class="tonedownload-card-desc">${escapeHtml(r.tone_description.substring(0, 120))}</div>` : ''}
            </div>
            <div class="tonedownload-card-actions">
                ${installed
                    ? '<span class="tonedownload-installed-badge">✓ Installed</span>'
                    : `<button class="btn btn-primary tonedownload-install-btn"
                              onclick="installToneModel('${escapeHtml(r.download_url)}', '${escapeHtml(r.name)}', ${r.size || 'null'}, '${escapeHtml(r.filename)}')">
                        Install
                       </button>`
                }
            </div>
        </div>`;
    }
    container.innerHTML = html;
}

async function installToneModel(downloadUrl, displayName, size, filename) {
    const btn = event.target;
    btn.disabled = true;
    btn.textContent = 'Downloading...';

    try {
        const data = await apiPost('/models/tonedownload/install', {
            download_url: downloadUrl,
            name: filename || displayName + '.nam',
            display_name: displayName,
            size: size,
        });
        markInstalled(downloadUrl);
        btn.textContent = '✓ Done';
        btn.style.background = 'var(--success)';
        btn.style.borderColor = 'var(--success)';
        // Refresh model list
        loadModels();
    } catch (e) {
        btn.disabled = false;
        btn.textContent = 'Install';
        alert('Install failed: ' + e.message);
    }
}

