/**
 * network.js — WiFi scan, connect, hotspot management for Pi Multi-FX Pedal.
 *
 * Relies on apiGet, apiPost from app.js and the pedalWS singleton.
 */

/* ── WiFi Status ────────────────────────────────────────────────── */

async function refreshWiFiStatus() {
    try {
        const status = await apiGet('/wifi/status');
        const ssidEl = document.getElementById('wifi-ssid');
        const ipEl = document.getElementById('wifi-ip');
        const sigEl = document.getElementById('wifi-signal-text');
        const iconEl = document.getElementById('wifi-icon');

        if (status.connected && status.ssid) {
            ssidEl.textContent = status.ssid;
            ipEl.textContent = status.ip || 'No IP';
            sigEl.textContent = `${status.signal || 0}%`;
            // Signal bars
            const sig = status.signal || 0;
            if (sig > 70) iconEl.textContent = '📶';
            else if (sig > 40) iconEl.textContent = '📶';
            else if (sig > 15) iconEl.textContent = '📶';
            else iconEl.textContent = '📶';
        } else {
            ssidEl.textContent = 'Not connected';
            ipEl.textContent = '—';
            sigEl.textContent = '—';
            iconEl.textContent = '📡';
        }
    } catch (e) {
        console.warn('Failed to get WiFi status:', e);
        document.getElementById('wifi-ssid').textContent = 'Error';
    }
}

/* ── WiFi Scan ──────────────────────────────────────────────────── */

async function scanWiFi() {
    const btn = document.getElementById('wifi-scan-btn');
    const results = document.getElementById('wifi-scan-results');
    btn.disabled = true;
    btn.textContent = 'Scanning...';
    results.innerHTML = '<div class="loading">Scanning for networks...</div>';

    try {
        const data = await apiGet('/wifi/scan');
        const networks = data.networks || [];

        if (networks.length === 0) {
            results.innerHTML = '<div class="hint">No networks found. Make sure WiFi is enabled.</div>';
            return;
        }

        let html = '<div class="network-list">';
        for (const net of networks) {
            const bars = signalBars(net.signal);
            const encClass = net.encryption === 'Open' ? 'enc-open' : 'enc-secure';
            const displayEnc = net.encryption === 'Open' ? 'Open' : 'Secured';
            html += `
                <div class="network-item">
                    <div class="network-item-icon">${bars}</div>
                    <div class="network-item-info">
                        <div class="network-item-ssid">${escapeHtml(net.ssid)}</div>
                        <div class="network-item-meta"><span class="${encClass}">${displayEnc}</span> · ${net.signal}%</div>
                    </div>
                    <button class="btn btn-primary" onclick="openWiFiConnect('${escapeHtml(net.ssid)}')">Connect</button>
                </div>`;
        }
        html += '</div>';
        results.innerHTML = html;
    } catch (e) {
        console.warn('WiFi scan failed:', e);
        results.innerHTML = '<div class="network-error">Scan failed. Check WiFi hardware.</div>';
    } finally {
        btn.disabled = false;
        btn.textContent = 'Scan';
    }
}

function signalBars(signal) {
    if (signal > 70) return '📶';
    if (signal > 40) return '📶';
    if (signal > 15) return '📶';
    return '📶';
}

/* ── WiFi Connect Modal ─────────────────────────────────────────── */

let pendingSSID = '';

function openWiFiConnect(ssid) {
    pendingSSID = ssid;
    document.getElementById('wifi-modal-ssid').textContent = ssid;
    document.getElementById('wifi-modal-password').value = '';
    document.getElementById('wifi-modal-error').textContent = '';
    document.getElementById('wifi-connect-modal').style.display = 'flex';
}

function closeWiFiModal() {
    document.getElementById('wifi-connect-modal').style.display = 'none';
    pendingSSID = '';
}

async function connectWiFi() {
    const password = document.getElementById('wifi-modal-password').value;
    const errorEl = document.getElementById('wifi-modal-error');

    if (!password) {
        errorEl.textContent = 'Please enter a password.';
        return;
    }

    errorEl.textContent = 'Connecting...';
    try {
        const result = await apiPost('/wifi/connect', { ssid: pendingSSID, password });
        if (result.ok) {
            errorEl.textContent = 'Connected!';
            setTimeout(() => {
                closeWiFiModal();
                refreshWiFiStatus();
            }, 1500);
        } else {
            errorEl.textContent = result.error || 'Connection failed.';
        }
    } catch (e) {
        errorEl.textContent = 'Network error: ' + (e.message || 'Unknown');
    }
}

/* ── Saved Networks ─────────────────────────────────────────────── */

async function loadSavedNetworks() {
    const list = document.getElementById('wifi-saved-list');
    try {
        const data = await apiGet('/wifi/saved');
        const networks = data.networks || [];

        if (networks.length === 0) {
            list.innerHTML = '<div class="hint">No saved networks.</div>';
            return;
        }

        let html = '<div class="network-list">';
        for (const net of networks) {
            html += `
                <div class="network-item">
                    <div class="network-item-info">
                        <div class="network-item-ssid">${escapeHtml(net.ssid)}</div>
                        <div class="network-item-meta">Saved</div>
                    </div>
                    <button class="btn btn-danger btn-sm" onclick="forgetNetwork('${escapeHtml(net.ssid)}')">Forget</button>
                </div>`;
        }
        html += '</div>';
        list.innerHTML = html;
    } catch (e) {
        console.warn('Failed to load saved networks:', e);
        list.innerHTML = '<div class="network-error">Failed to load.</div>';
    }
}

async function forgetNetwork(ssid) {
    if (!confirm(`Forget "${ssid}"?`)) return;
    try {
        await apiPost('/wifi/forget', { ssid });
        loadSavedNetworks();
        refreshWiFiStatus();
    } catch (e) {
        console.warn('Failed to forget network:', e);
    }
}

/* ── Hotspot ────────────────────────────────────────────────────── */

async function enableHotspot() {
    const ssid = document.getElementById('hotspot-ssid').value.trim();
    const psk = document.getElementById('hotspot-psk').value.trim();
    const errorEl = document.getElementById('wifi-modal-error');

    if (!ssid) { alert('SSID is required.'); return; }
    if (psk.length < 8) { alert('Password must be at least 8 characters.'); return; }

    const btn = document.getElementById('hotspot-enable-btn');
    btn.disabled = true;
    btn.textContent = 'Enabling...';

    try {
        const result = await apiPost('/wifi/hotspot/enable', { ssid, password: psk });
        if (result.ok) {
            refreshWiFiStatus();
            updateHotspotUI(true, ssid);
        } else {
            alert('Failed: ' + (result.error || 'Unknown error'));
        }
    } catch (e) {
        alert('Network error: ' + e.message);
    } finally {
        btn.disabled = false;
        btn.textContent = 'Enable Hotspot';
    }
}

async function disableHotspot() {
    const btn = document.getElementById('hotspot-disable-btn');
    btn.disabled = true;
    btn.textContent = 'Disabling...';

    try {
        const result = await apiPost('/wifi/hotspot/disable');
        if (result.ok) {
            refreshWiFiStatus();
            updateHotspotUI(false);
        }
    } catch (e) {
        alert('Network error: ' + e.message);
    } finally {
        btn.disabled = false;
        btn.textContent = 'Disable Hotspot';
    }
}

function updateHotspotUI(active, ssid) {
    const indicator = document.getElementById('hotspot-status-indicator');
    const clients = document.getElementById('hotspot-clients');
    if (active) {
        indicator.textContent = 'Active';
        indicator.className = 'hotspot-indicator hotspot-on';
        document.getElementById('hotspot-ssid-row').querySelector('input').value = ssid || 'Pi-Pedal';
    } else {
        indicator.textContent = 'Off';
        indicator.className = 'hotspot-indicator hotspot-off';
        clients.textContent = '0';
    }
}

/* ── Helpers ────────────────────────────────────────────────────── */

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

/* ── WebSocket listeners ────────────────────────────────────────── */

pedalWS.on('network_changed', (msg) => {
    refreshWiFiStatus();
});

/* ── Initial load ───────────────────────────────────────────────── */

// Auto-load when the network tab is first activated (handled by switchTab)
// But also check if we're already on the settings page
if (document.getElementById('tab-network')) {
    // Defer to DOMContentLoaded in settings.html → switchTab call
}