/**
 * presets.js — Preset Manager page: browse banks, load/save/edit.
 */

let currentBank = 0;
let currentProgram = 0;

async function loadPresets() {
    const container = document.getElementById('bank-list');
    container.innerHTML = '<p class="loading">Loading...</p>';

    try {
        const data = await apiGet('/presets');
        renderBanks(container, data.banks);
    } catch (e) {
        container.innerHTML = `<p class="text-muted">Error loading presets: ${e.message}</p>`;
    }
}

function renderBanks(container, banks) {
    if (!banks || banks.length === 0) {
        container.innerHTML = '<p class="text-muted">No presets found. Create one from the Dashboard.</p>';
        return;
    }

    let html = '';
    for (const bank of banks) {
        html += `<div class="bank-section" data-bank="${bank.number}">`;
        html += `<div class="bank-header">${bank.name}</div>`;
        html += '<div class="preset-grid">';
        for (let i = 0; i < 4; i++) {
            const p = bank.presets && bank.presets[i];
            if (p) {
                const active = (p.bank === currentBank && p.program === currentProgram);
                html += `<div class="preset-card ${active ? 'active' : ''}" 
                              onclick="openPreset(${bank.number}, ${i})">`;
                html += `<div class="preset-card-name">${escapeHtml(p.name)}</div>`;
                html += `<div class="preset-card-slot">Bank ${bank.number} · ${i}</div>`;
                html += '</div>';
            } else {
                html += `<div class="preset-card" style="opacity:0.4; cursor:default">
                            <div class="preset-card-name">— Empty —</div>
                            <div class="preset-card-slot">Slot ${i}</div>
                         </div>`;
            }
        }
        html += '</div></div>';
    }
    container.innerHTML = html;
}

async function openPreset(bank, program) {
    currentBank = bank;
    currentProgram = program;

    try {
        const preset = await apiGet(`/presets/${bank}/${program}`);
        const modal = document.getElementById('preset-modal');
        const title = document.getElementById('modal-title');
        const body = document.getElementById('modal-body');

        title.textContent = `Edit: ${preset.name}`;
        body.innerHTML = renderPresetForm(preset);

        modal.style.display = 'flex';
    } catch (e) {
        console.error('Error loading preset:', e);
    }
}

function renderPresetForm(preset) {
    let html = `
        <div class="param-row">
            <span class="param-label">Name</span>
            <input type="text" id="edit-preset-name" value="${escapeHtml(preset.name)}" 
                   style="flex:1; background:var(--bg-secondary); border:1px solid var(--border);
                          color:var(--text-primary); padding:4px 8px; border-radius:4px;">
        </div>
        <div class="param-row">
            <span class="param-label">Volume</span>
            <input type="range" class="slider" id="edit-volume" min="0" max="100"
                   value="${Math.round((preset.master_volume || 0.8) * 100)}"
                   oninput="document.getElementById('edit-volume-text').textContent=this.value+'%'">
            <span class="param-value" id="edit-volume-text">${Math.round((preset.master_volume || 0.8) * 100)}%</span>
        </div>
        <hr style="border-color:var(--border); margin:10px 0;">
        <div style="font-size:0.85rem; color:var(--text-secondary); margin-bottom:8px;">FX Chain:</div>
    `;

    if (preset.chain && preset.chain.length > 0) {
        for (const block of preset.chain) {
            const label = block.fx_type.replace(/_/g, ' ');
            const badged = block.enabled && !block.bypass
                ? `<span class="fx-badge" style="background:var(--success)">ON</span>`
                : `<span class="fx-badge" style="background:var(--text-muted)">OFF</span>`;
            html += `<div class="param-row" style="justify-content:space-between">
                        <span style="text-transform:capitalize; font-size:0.8rem;">${label} ${badged}</span>
                     </div>`;
        }
    } else {
        html += `<p class="text-muted" style="font-size:0.8rem;">No FX blocks in chain</p>`;
    }

    return html;
}

async function savePreset() {
    const modal = document.getElementById('preset-modal');
    if (!modal || modal.style.display === 'none') return;

    const nameInput = document.getElementById('edit-preset-name');
    const volSlider = document.getElementById('edit-volume');

    const name = nameInput ? nameInput.value : 'Preset';
    const volume = volSlider ? parseInt(volSlider.value) / 100 : 0.8;

    try {
        // Fetch current preset data, update name/volume, re-save
        const preset = await apiGet(`/presets/${currentBank}/${currentProgram}`);
        preset.name = name;
        preset.master_volume = volume;

        await apiPut(`/presets/${currentBank}/${currentProgram}`, preset);
        closeModal();
        loadPresets();
    } catch (e) {
        console.error('Error saving preset:', e);
    }
}

async function deletePreset() {
    if (!confirm('Delete this preset?')) return;
    try {
        await apiDelete(`/presets/${currentBank}/${currentProgram}`);
        closeModal();
        loadPresets();
    } catch (e) {
        console.error('Error deleting preset:', e);
    }
}

async function activateFromPresetPage(bank, program) {
    try {
        await apiPost(`/presets/${bank}/${program}/activate`);
        currentBank = bank;
        currentProgram = program;
        loadPresets();
    } catch (e) {
        console.error('Error activating:', e);
    }
}

function closeModal(event) {
    const modal = document.getElementById('preset-modal');
    if (event && event.target !== modal) return;  // only close on overlay click
    modal.style.display = 'none';
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Load on page ready
document.addEventListener('DOMContentLoaded', loadPresets);