// USB Server Web UI

const API_BASE = '';

// Tab navigation
document.querySelectorAll('.tab').forEach(tab => {
    tab.addEventListener('click', () => {
        document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
        tab.classList.add('active');
        document.getElementById('tab-' + tab.dataset.tab).classList.add('active');
    });
});

// Status updates
async function updateStatus() {
    try {
        const resp = await fetch(API_BASE + '/api/status');
        const data = await resp.json();

        const el = document.getElementById('status');
        if (data.connected) {
            el.textContent = 'Verbunden';
            el.className = 'status connected';
        } else {
            el.textContent = 'Nicht verbunden';
            el.className = 'status disconnected';
        }

        const modeNames = {
            share: 'Freigeben',
            use: 'Empfangen',
            both: 'Freigeben und Empfangen',
        };
        document.getElementById('mode-info').innerHTML =
            `<strong>Modus:</strong> ${escapeHtml(modeNames[data.mode] || data.mode)} | ` +
            `<strong>Name:</strong> ${escapeHtml(data.name)} | ` +
            `<strong>Client ID:</strong> ${data.client_id ? escapeHtml(data.client_id.substring(0, 8)) + '...' : '-'}` +
            (data.encrypted ? ' | <strong>Tunnel:</strong> verschluesselt'
                            : ' | <strong>Tunnel:</strong> unverschluesselt (keine Tokens)');
    } catch (e) {
        const el = document.getElementById('status');
        el.textContent = 'Fehler';
        el.className = 'status disconnected';
    }
}

// Device list
async function updateDevices() {
    try {
        const resp = await fetch(API_BASE + '/api/devices');
        const data = await resp.json();
        renderDevices(data);
    } catch (e) {
        document.getElementById('device-list').innerHTML =
            '<p class="loading">Fehler beim Laden der Geraete</p>';
    }
}

function renderDevices(data) {
    const container = document.getElementById('device-list');

    // In "both" mode show remote devices first — those are the ones you act
    // on — then the local devices this machine offers.
    let html = '';
    if (data.available_devices || data.attached_devices) {
        html += renderUseSection(data.available_devices || [], data.attached_devices || []);
    }
    if (data.local_devices) {
        if (html) {
            html += '<div class="client-header">Eigene Geraete (freigegeben)</div>';
        }
        html += renderShareSection(data.local_devices);
    }

    container.innerHTML = html || '<p class="no-devices">Keine Geraete</p>';
}

function renderShareSection(devices) {
    if (!devices || devices.length === 0) {
        return '<p class="no-devices">Keine USB-Geraete gefunden</p>';
    }

    return devices.map(dev => `
        <div class="device-card">
            <div class="device-info">
                <div class="device-name">${escapeHtml(dev.name)}</div>
                <div class="device-details">
                    <span>Bus: ${escapeHtml(dev.bus_id)}</span>
                    <span>VID:PID: ${escapeHtml(dev.vendor_id)}:${escapeHtml(dev.product_id)}</span>
                    <span>Speed: ${speedName(dev.speed)}</span>
                </div>
            </div>
            <div class="device-status">
                <span class="badge ${dev.status === 'available' ? 'available' : 'in-use'}">
                    ${dev.status === 'available' ? 'Verfuegbar' : 'In Benutzung'}
                </span>
            </div>
        </div>
    `).join('');
}

function renderUseSection(available, attached) {
    let html = '';

    // Attached devices first
    if (attached && attached.length > 0) {
        html += '<div class="client-header">Verbundene Geraete</div>';
        html += attached.map(dev => `
            <div class="device-card">
                <div class="device-info">
                    <div class="device-name">${escapeHtml(dev.name || dev.bus_id)}</div>
                    <div class="device-details">
                        <span>Von: ${escapeHtml(dev.client_name || dev.client_id)}</span>
                        ${dev.vendor_id ? `<span>VID:PID: ${escapeHtml(dev.vendor_id)}:${escapeHtml(dev.product_id)}</span>` : ''}
                        <span>VHCI Port: ${escapeHtml(dev.vhci_port)}</span>
                    </div>
                </div>
                <div class="device-status">
                    <label class="auto-connect-label" title="Beim Start automatisch verbinden">
                        <input type="checkbox" ${dev.auto_connect ? 'checked' : ''}
                            onchange="toggleAutoConnect('${jsArg(dev.vendor_id)}', '${jsArg(dev.product_id)}', this.checked)">
                        Autostart
                    </label>
                    <span class="badge attached">Verbunden</span>
                    <button class="btn small danger" onclick="detachDevice('${jsArg(dev.client_id)}', '${jsArg(dev.bus_id)}')">Trennen</button>
                </div>
            </div>
        `).join('');
    }

    // Group available by client
    const byClient = {};
    (available || []).forEach(dev => {
        const key = dev.client_id;
        if (!byClient[key]) {
            byClient[key] = { name: dev.client_name, devices: [] };
        }
        byClient[key].devices.push(dev);
    });

    if (Object.keys(byClient).length === 0 && (!attached || attached.length === 0)) {
        return '<p class="no-devices">Keine fremden Geraete verfuegbar. Warte auf Share-Clients...</p>';
    }

    for (const [clientId, info] of Object.entries(byClient)) {
        html += `<div class="client-header">${escapeHtml(info.name)} (${escapeHtml(clientId.substring(0, 8))}...)</div>`;
        html += info.devices.map(dev => {
            const isAttached = (attached || []).some(a =>
                a.bus_id === dev.bus_id && a.client_id === clientId
            );
            return `
                <div class="device-card">
                    <div class="device-info">
                        <div class="device-name">${escapeHtml(dev.name)}</div>
                        <div class="device-details">
                            <span>Bus: ${escapeHtml(dev.bus_id)}</span>
                            <span>VID:PID: ${escapeHtml(dev.vendor_id)}:${escapeHtml(dev.product_id)}</span>
                            <span>Speed: ${speedName(dev.speed)}</span>
                        </div>
                    </div>
                    <div class="device-status">
                        ${dev.status === 'in_use'
                            ? `<span class="badge in-use">In Benutzung</span>
                               ${dev.allow_force_detach ? `<button class="btn small danger" onclick="forceDetach('${jsArg(clientId)}', '${jsArg(dev.bus_id)}')">Trennen</button>` : ''}`
                            : isAttached
                                ? '<span class="badge attached">Verbunden</span>'
                                : `<span class="badge available">Verfuegbar</span>
                                   <button class="btn small primary" onclick="attachDevice('${jsArg(clientId)}', '${jsArg(dev.bus_id)}')">Verbinden</button>`
                        }
                    </div>
                </div>
            `;
        }).join('');
    }

    return html;
}

// Attach/Detach
async function attachDevice(clientId, busId) {
    try {
        const resp = await fetch(API_BASE + '/api/attach', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ client_id: clientId, bus_id: busId })
        });
        const data = await resp.json();
        if (!data.ok) {
            alert('Fehler: ' + (data.error || 'Unbekannt'));
        }
        updateDevices();
    } catch (e) {
        alert('Verbindungsfehler: ' + e.message);
    }
}

async function detachDevice(clientId, busId) {
    try {
        const resp = await fetch(API_BASE + '/api/detach', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ client_id: clientId, bus_id: busId })
        });
        const data = await resp.json();
        if (!data.ok) {
            alert('Fehler: ' + (data.error || 'Unbekannt'));
        }
        updateDevices();
    } catch (e) {
        alert('Verbindungsfehler: ' + e.message);
    }
}

// Force detach
async function forceDetach(clientId, busId) {
    try {
        const resp = await fetch(API_BASE + '/api/force-detach', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ client_id: clientId, bus_id: busId })
        });
        const data = await resp.json();
        if (!data.ok) {
            alert('Fehler: ' + (data.error || 'Unbekannt'));
        }
        updateDevices();
    } catch (e) {
        alert('Verbindungsfehler: ' + e.message);
    }
}

// Auto-connect toggle
async function toggleAutoConnect(vendorId, productId, enabled) {
    try {
        const resp = await fetch(API_BASE + '/api/auto-connect', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ vendor_id: vendorId, product_id: productId, enabled: enabled })
        });
        const data = await resp.json();
        if (!data.ok) {
            alert('Fehler: ' + (data.error || 'Unbekannt'));
            updateDevices();
        }
    } catch (e) {
        alert('Fehler: ' + e.message);
        updateDevices();
    }
}

// Settings
async function loadSettings() {
    try {
        const resp = await fetch(API_BASE + '/api/config');
        const cfg = await resp.json();
        document.getElementById('relay-addr').value = cfg.relay_addr || '';
        document.getElementById('hash').value = cfg.hash || '';
        document.getElementById('mode').value = cfg.mode || 'use';
        document.getElementById('client-name').value = cfg.name || '';
        document.getElementById('web-port').value = cfg.web_port || 8080;
        document.getElementById('allow-force-detach').checked = cfg.allow_force_detach || false;
        document.getElementById('direct-port').value = cfg.direct_port || 0;
        document.getElementById('disable-direct').checked = cfg.disable_direct || false;
        document.getElementById('token1').value = cfg.token1 || '';
        document.getElementById('token2').value = cfg.token2 || '';
        document.getElementById('token3').value = cfg.token3 || '';
        if (cfg.hash) {
            document.getElementById('computed-hash').textContent = cfg.hash;
        }
    } catch (e) {
        console.error('Failed to load settings:', e);
    }
}

document.getElementById('settings-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
        const resp = await fetch(API_BASE + '/api/config', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                relay_addr: document.getElementById('relay-addr').value,
                mode: document.getElementById('mode').value,
                name: document.getElementById('client-name').value,
                web_port: parseInt(document.getElementById('web-port').value),
                allow_force_detach: document.getElementById('allow-force-detach').checked,
                direct_port: parseInt(document.getElementById('direct-port').value) || 0,
                disable_direct: document.getElementById('disable-direct').checked,
            })
        });
        const data = await resp.json();
        if (data.ok) {
            alert('Einstellungen gespeichert. Neustart erforderlich fuer Aenderungen.');
        } else {
            alert('Fehler: ' + (data.error || 'Unbekannt'));
        }
    } catch (e) {
        alert('Fehler: ' + e.message);
    }
});

// Token generation
document.getElementById('generate-tokens').addEventListener('click', async () => {
    try {
        const resp = await fetch(API_BASE + '/api/generate-token', { method: 'POST' });
        const data = await resp.json();
        document.getElementById('token1').value = data.token1;
        document.getElementById('token2').value = data.token2;
        document.getElementById('token3').value = data.token3;
        document.getElementById('computed-hash').textContent = data.hash;
        document.getElementById('hash').value = data.hash;
    } catch (e) {
        alert('Fehler: ' + e.message);
    }
});

document.getElementById('apply-tokens').addEventListener('click', async () => {
    const token1 = document.getElementById('token1').value;
    const token2 = document.getElementById('token2').value;
    const token3 = document.getElementById('token3').value;

    if (!token1 || !token2 || !token3) {
        alert('Bitte alle 3 Tokens eingeben');
        return;
    }

    try {
        const resp = await fetch(API_BASE + '/api/apply-tokens', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ token1, token2, token3 })
        });
        const data = await resp.json();
        if (data.ok) {
            document.getElementById('computed-hash').textContent = data.hash;
            document.getElementById('hash').value = data.hash;
            alert('Tokens angewandt. Hash: ' + data.hash.substring(0, 16) + '...');
        } else {
            alert('Fehler: ' + (data.error || 'Unbekannt'));
        }
    } catch (e) {
        alert('Fehler: ' + e.message);
    }
});

// Service management
document.getElementById('install-service').addEventListener('click', async () => {
    try {
        const resp = await fetch(API_BASE + '/api/service/install', { method: 'POST' });
        const data = await resp.json();
        document.getElementById('service-status').textContent = data.message || data.error;
    } catch (e) {
        document.getElementById('service-status').textContent = 'Fehler: ' + e.message;
    }
});

document.getElementById('uninstall-service').addEventListener('click', async () => {
    try {
        const resp = await fetch(API_BASE + '/api/service/uninstall', { method: 'POST' });
        const data = await resp.json();
        document.getElementById('service-status').textContent = data.message || data.error;
    } catch (e) {
        document.getElementById('service-status').textContent = 'Fehler: ' + e.message;
    }
});

// Helpers
function speedName(speed) {
    const names = { 1: 'Low (1.5M)', 2: 'Full (12M)', 3: 'High (480M)', 5: 'Super (5G)', 6: 'Super+ (10G)' };
    return names[speed] || 'Unknown';
}

function escapeHtml(str) {
    if (str === null || str === undefined) return '';
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}

// jsArg escapes a value for use inside a single-quoted JavaScript string that
// itself sits in an HTML attribute. Bus IDs, client IDs and vendor strings all
// arrive from remote peers, so interpolating them raw would let another client
// in the group inject script into this UI.
function jsArg(str) {
    if (str === null || str === undefined) return '';
    return String(str)
        .replace(/\\/g, '\\\\')
        .replace(/'/g, "\\'")
        .replace(/"/g, '&quot;')
        .replace(/</g, '\\x3c')
        .replace(/>/g, '\\x3e')
        .replace(/&/g, '\\x26');
}

// Init
loadSettings();
updateStatus();
updateDevices();

// Periodic updates
setInterval(updateStatus, 5000);
setInterval(updateDevices, 3000);
