/**
 * irs.js — IR Manager page.
 */

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

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

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

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

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

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

    let html = '';
    for (const ir of data.irs) {
        const isLoaded = ir.name === currentName;
        html += `<div class="ir-item ${isLoaded ? 'loaded' : ''}">`;
        html += `<div>
                    <div class="ir-name">${escapeHtml(ir.name)}</div>
                    <div class="ir-meta">
                        ${ir.num_taps} taps · ${ir.length_ms}ms @ ${ir.sample_rate}Hz
                        ${isLoaded ? '· <strong style="color:var(--success)">CURRENT</strong>' : ''}
                    </div>
                 </div>`;
        if (!isLoaded) {
            html += `<button class="btn btn-primary" onclick='loadIR(${JSON.stringify(ir.path)})'
                             style="padding:4px 10px; font-size:0.78rem;">Load</button>`;
        }
        html += '</div>';
    }
    listEl.innerHTML = html;
}

async function loadIR(path) {
    try {
        await apiPost('/irs/load', { path });
        loadIRs();
    } catch (e) {
        alert('Failed to load IR: ' + e.message);
    }
}

async function unloadIR() {
    try {
        await apiPost('/irs/unload');
        loadIRs();
    } catch (e) {
        alert('Failed to unload: ' + e.message);
    }
}

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

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

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

document.addEventListener('DOMContentLoaded', loadIRs);

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

const INSTALLED_IRS_KEY = 'tonedownload_installed_irs';

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

function markIRInstalled(url) {
    const installed = getInstalledIRs();
    if (!installed.includes(url)) {
        installed.push(url);
        localStorage.setItem(INSTALLED_IRS_KEY, JSON.stringify(installed));
    }
}

function isIRInstalled(url) {
    return getInstalledIRs().includes(url);
}

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

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

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

    loaderEl.style.display = 'block';

    try {
        const data = await apiGet('/irs/tonedownload/search?q=' + encodeURIComponent(query));
        loaderEl.style.display = 'none';
        renderToneIRResults(resultsEl, data.results || []);
    } 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 loadTrendingIRs() {
    const resultsEl = document.getElementById('ir-tone-results');
    const loaderEl = document.getElementById('ir-tone-loader');
    const offlineEl = document.getElementById('ir-tone-offline');

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

    try {
        const data = await apiGet('/irs/tonedownload/search?q=');
        loaderEl.style.display = 'none';
        renderToneIRResults(resultsEl, data.results || []);
    } 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 renderToneIRResults(container, results) {
    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 = isIRInstalled(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)}
                </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="installToneIR('${escapeHtml(r.download_url)}', '${escapeHtml(r.name)}', ${r.size || 'null'}, '${escapeHtml(r.filename)}')">
                        Install
                       </button>`
                }
            </div>
        </div>`;
    }
    container.innerHTML = html;
}

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

    try {
        await apiPost('/irs/tonedownload/install', {
            download_url: downloadUrl,
            name: filename || displayName + '.wav',
            display_name: displayName,
            size: size,
        });
        markIRInstalled(downloadUrl);
        btn.textContent = '✓ Done';
        btn.style.background = 'var(--success)';
        btn.style.borderColor = 'var(--success)';
        loadIRs();
    } catch (e) {
        btn.disabled = false;
        btn.textContent = 'Install';
        alert('Install failed: ' + e.message);
    }
}