<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Meshtastic Configuration Dashboard</title>
    
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet">
    
    <style>
    /* -------------------------------------------------------------------------- */
    /* RUSJP DESIGN SYSTEM (Teal/Dark Theme)                                      */
    /* -------------------------------------------------------------------------- */
    :root {
        --primary-color: #00d4aa;
        --primary-hover: #00b89f;
        --bg-primary: #0f172a;
        --bg-secondary: #1e293b;
        --bg-tertiary: #334155;
        --text-primary: #f1f5f9;
        --text-secondary: #94a3b8;
        --border-color: #334155;
        --divider-color: #1e293b;
        --danger: #ef4444;
        --warning: #f59e0b;
        --success: #10b981;
        --info: #3b82f6;
        --radius-sm: 6px;
        --radius-md: 8px;
        --spacing-md: 1rem;
    }

    body {
        background-color: var(--bg-primary);
        color: var(--text-primary);
        font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
        margin: 0;
        line-height: 1.6;
    }

    .dashboard { padding: 20px; max-width: 1600px; margin: 0 auto; }
    
    .header { 
        display: flex; justify-content: space-between; align-items: center; 
        margin-bottom: 25px; padding-bottom: 20px; border-bottom: 1px solid var(--border-color); 
    }
    .header h1 { 
        font-size: 1.5rem; color: var(--text-primary); margin: 0; 
        display: flex; align-items: center; gap: 12px; 
    }
    .highlight { color: var(--primary-color); }

    .main-grid {
        display: grid;
        grid-template-columns: 260px 1fr;
        gap: 25px;
        align-items: start;
    }

    .card {
        background: var(--bg-secondary);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        overflow: hidden;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2);
    }
    .card-header { 
        padding: 15px 20px; border-bottom: 1px solid var(--border-color); 
        background: rgba(0,0,0,0.15); 
    }
    .card-header h2 { 
        margin: 0; font-size: 1.1rem; color: var(--primary-color); 
        display: flex; align-items: center; gap: 10px; 
    }
    .card-content { padding: 25px; }

    .settings-nav-menu { display: flex; flex-direction: column; }
    .settings-nav-item {
        display: flex; align-items: center; gap: 12px; padding: 14px 20px;
        background: transparent; border: none; border-bottom: 1px solid var(--border-color);
        color: var(--text-secondary); cursor: pointer; text-align: left; 
        font-size: 0.95rem; font-weight: 500; transition: all 0.2s;
    }
    .settings-nav-item:hover { 
        background: rgba(0, 212, 170, 0.05); color: var(--text-primary); 
    }
    .settings-nav-item.active { 
        background: rgba(0, 212, 170, 0.1); color: var(--primary-color); 
        border-left: 3px solid var(--primary-color); font-weight: 600; 
    }
    .settings-nav-item i { width: 24px; text-align: center; font-size: 1.1em; }

    .settings-form-section { display: none; animation: fadeIn 0.3s ease; }
    .settings-form-section.active { display: block; }
    @keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }

    .settings-description {
        background: rgba(0, 212, 170, 0.05); border-left: 4px solid var(--primary-color);
        padding: 15px 20px; margin-bottom: 30px; border-radius: 4px; 
        color: var(--text-secondary); font-size: 0.95rem;
    }

    .setting-item {
        display: grid; grid-template-columns: 1fr 350px; gap: 30px;
        padding: 20px; margin-bottom: 15px;
        background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: var(--radius-sm);
        align-items: start; transition: border-color 0.2s;
    }
    .setting-item:hover { border-color: #475569; }

    .setting-info { flex: 1; }
    .setting-label { 
        font-weight: 600; color: var(--text-primary); margin-bottom: 8px; 
        display: flex; align-items: center; gap: 10px; font-size: 1rem; 
    }
    .setting-help { color: var(--text-secondary); font-size: 0.85rem; line-height: 1.5; }
    .setting-help strong { color: var(--text-primary); }
    .setting-help .tip { display: block; margin-top: 6px; color: var(--info); font-style: italic; }
    .setting-help .warning { color: var(--warning); font-weight: 600; }
    .setting-help .danger { color: var(--danger); font-weight: 600; }

    select, input[type="text"], input[type="number"], input[type="password"] {
        width: 100%; padding: 10px 12px; background: var(--bg-tertiary);
        border: 1px solid var(--border-color); border-radius: 4px; 
        color: var(--text-primary); font-family: inherit; font-size: 0.95rem;
        box-sizing: border-box; transition: all 0.2s;
    }
    select:focus, input:focus { 
        outline: none; border-color: var(--primary-color); 
        box-shadow: 0 0 0 2px rgba(0, 212, 170, 0.15); 
    }

    .checkbox-wrapper { display: flex; align-items: center; gap: 12px; height: 100%; cursor: pointer; }
    .checkbox-wrapper input[type="checkbox"] { 
        width: 20px; height: 20px; accent-color: var(--primary-color); cursor: pointer; 
    }
    .checkbox-wrapper label { cursor: pointer; font-weight: 500; user-select: none; }

    .slider-wrapper { width: 100%; }
    .slider-container { display: flex; align-items: center; gap: 15px; margin-bottom: 8px; }
    .slider-container input[type="range"] { 
        flex: 1; height: 6px; background: var(--border-color); border-radius: 3px; 
        appearance: none; outline: none; cursor: pointer; 
    }
    .slider-container input[type="range"]::-webkit-slider-thumb { 
        appearance: none; width: 18px; height: 18px; background: var(--primary-color); 
        border-radius: 50%; cursor: pointer; transition: transform 0.1s; 
    }
    .slider-container input[type="range"]::-webkit-slider-thumb:hover { transform: scale(1.2); }
    .slider-value { 
        min-width: 70px; text-align: right; font-weight: 700; color: var(--primary-color); 
        font-family: monospace; font-size: 1rem;
    }
    .slider-labels { display: flex; justify-content: space-between; font-size: 0.75rem; color: var(--text-secondary); }

    .input-with-actions { display: flex; gap: 8px; }
    .input-action-btn {
        padding: 0 14px; background: var(--bg-tertiary); border: 1px solid var(--border-color);
        color: var(--text-secondary); border-radius: 4px; cursor: pointer; transition: 0.2s;
        display: flex; align-items: center; justify-content: center;
    }
    .input-action-btn:hover { color: var(--primary-color); border-color: var(--primary-color); }

    .form-actions { 
        margin-top: 30px; padding-top: 20px; border-top: 1px solid var(--border-color); 
        display: flex; gap: 15px; 
    }
    .btn { 
        padding: 10px 24px; border-radius: 4px; font-weight: 600; cursor: pointer; 
        transition: all 0.2s; border: none; font-size: 0.95rem; 
        display: inline-flex; align-items: center; gap: 8px; 
    }
    .btn-primary { background: var(--primary-color); color: var(--bg-primary); }
    .btn-primary:hover { background: var(--primary-hover); transform: translateY(-1px); }
    .btn-secondary { background: transparent; border: 1px solid var(--border-color); color: var(--text-primary); }
    .btn-secondary:hover { border-color: var(--primary-color); color: var(--primary-color); }
    .btn-danger { background: rgba(239, 68, 68, 0.15); color: var(--danger); border: 1px solid var(--danger); }
    .btn-danger:hover { background: var(--danger); color: white; }
    .btn-success { background: rgba(16, 185, 129, 0.15); color: var(--success); border: 1px solid var(--success); }
    .btn-success:hover { background: var(--success); color: white; }

    .badge { 
        padding: 2px 8px; border-radius: 4px; font-size: 0.7rem; font-weight: 800; 
        text-transform: uppercase; border: 1px solid; letter-spacing: 0.5px;
    }
    .badge-critical { color: var(--danger); border-color: var(--danger); background: rgba(239, 68, 68, 0.1); }
    .badge-warning { color: var(--warning); border-color: var(--warning); background: rgba(245, 158, 11, 0.1); }
    .badge-success { color: var(--success); border-color: var(--success); background: rgba(16, 185, 129, 0.1); }
    .badge-info { color: var(--info); border-color: var(--info); background: rgba(59, 130, 246, 0.1); }

    .channel-card-item { 
        background: var(--bg-primary); border: 1px solid var(--border-color); 
        border-radius: var(--radius-sm); padding: 25px; margin-bottom: 25px; 
    }
    .channel-header-row { 
        display: flex; justify-content: space-between; align-items: center; 
        margin-bottom: 20px; border-bottom: 1px solid var(--border-color); padding-bottom: 15px; 
    }
    .qr-section { 
        display: flex; gap: 30px; margin: 20px 0; padding: 20px; 
        background: rgba(0,0,0,0.2); border: 2px dashed var(--border-color); 
        border-radius: 8px; align-items: center; 
    }
    .qr-img { width: 140px; height: 140px; background: white; padding: 8px; border-radius: 4px; }
    .qr-img img { width: 100%; height: 100%; object-fit: contain; }

    .actions-grid { 
        display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); 
        gap: 20px; margin-top: 25px; 
    }
    .action-box { 
        text-align: center; padding: 30px 20px; background: var(--bg-primary); 
        border: 1px solid var(--border-color); border-radius: 8px; cursor: pointer; 
        transition: 0.2s; 
    }
    .action-box:hover { border-color: var(--primary-color); transform: translateY(-4px); }
    .action-icon { font-size: 2.5rem; margin-bottom: 15px; display: block; }

    .file-drop { 
        border: 2px dashed var(--border-color); padding: 40px; text-align: center; 
        border-radius: 8px; cursor: pointer; transition: 0.2s; background: var(--bg-primary); 
    }
    .file-drop:hover { border-color: var(--primary-color); background: rgba(0, 212, 170, 0.05); }

    .status-message { 
        position: fixed; top: 100px; right: 30px; padding: 15px 25px; 
        border-radius: 6px; z-index: 1000; display: none; animation: slideIn 0.3s; 
        font-weight: 600; box-shadow: 0 10px 25px rgba(0,0,0,0.5); 
    }
    .status-message.success { background: var(--success); color: #fff; }
    .status-message.error { background: var(--danger); color: #fff; }
    @keyframes slideIn { from { transform: translateX(100%); } to { transform: translateX(0); } }

    .loading-overlay {
        position: fixed; top: 0; left: 0; right: 0; bottom: 0;
        background: rgba(15, 23, 42, 0.9); display: none;
        justify-content: center; align-items: center; z-index: 2000;
        flex-direction: column; color: var(--primary-color);
    }
    .loading-overlay.active { display: flex; }

    @media (max-width: 1100px) {
        .main-grid { grid-template-columns: 1fr; }
        .settings-nav-menu { 
            flex-direction: row; overflow-x: auto; padding-bottom: 10px; 
            border-bottom: 1px solid var(--border-color); margin-bottom: 20px; 
        }
        .settings-nav-item { white-space: nowrap; border-bottom: none; border-radius: 4px; }
        .settings-nav-item.active { 
            border-left: none; background: var(--primary-color); color: var(--bg-primary); 
        }
        .setting-item { grid-template-columns: 1fr; gap: 15px; }
        .qr-section { flex-direction: column; text-align: center; }
    }
    </style>
</head>
<body>

    <div id="status-message" class="status-message"></div>
    <div class="loading-overlay" id="loading-overlay">
        <i class="fas fa-circle-notch fa-spin fa-3x"></i>
        <p style="margin-top: 15px; color: var(--text-primary);">Processing...</p>
    </div>

    <div class="dashboard">
        <header class="header">
            <div class="header-left">
                <h1>
                    <i class="fas fa-sliders-h"></i> 
                    Meshtastic <span class="highlight">Config</span>
                </h1>
            </div>
            <div class="header-right">
                <div id="node-info" style="display: flex; align-items: center; gap: 15px; background: rgba(0,0,0,0.2); padding: 8px 15px; border-radius: 20px; border: 1px solid var(--border-color);">
                    <i class="fas fa-broadcast-tower" style="color: var(--primary-color);"></i> 
                    <span id="node_name" style="font-weight: 700; color: var(--text-primary);">Loading...</span> 
                    <span class="badge badge-success">ONLINE</span>
                </div>
            </div>
        </header>

        <div class="main-grid">
            <div class="card">
                <div class="card-header">
                    <h2><i class="fas fa-bars"></i> Sections</h2>
                </div>
                <div class="card-content" style="padding: 0;">
                    <div class="settings-nav-menu" id="settings-nav">
                        <button class="settings-nav-item active" onclick="switchTab('device')"><i class="fas fa-microchip"></i> Device</button>
                        <button class="settings-nav-item" onclick="switchTab('lora')"><i class="fas fa-broadcast-tower"></i> LoRa</button>
                        <button class="settings-nav-item" onclick="switchTab('power')"><i class="fas fa-battery-full"></i> Power</button>
                        <button class="settings-nav-item" onclick="switchTab('position')"><i class="fas fa-map-marker-alt"></i> Position</button>
                        <button class="settings-nav-item" onclick="switchTab('network')"><i class="fas fa-wifi"></i> Network</button>
                        <button class="settings-nav-item" onclick="switchTab('display')"><i class="fas fa-desktop"></i> Display</button>
                        <button class="settings-nav-item" onclick="switchTab('bluetooth')"><i class="fab fa-bluetooth"></i> Bluetooth</button>
                        <button class="settings-nav-item" onclick="switchTab('security')"><i class="fas fa-shield-alt"></i> Security</button>
                        <button class="settings-nav-item" onclick="switchTab('channels')"><i class="fas fa-sitemap"></i> Channels</button>
                        <button class="settings-nav-item" onclick="switchTab('modules')"><i class="fas fa-puzzle-piece"></i> Modules</button>
                        <button class="settings-nav-item" onclick="switchTab('actions')"><i class="fas fa-tools"></i> Actions</button>
                    </div>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <h2 id="current-section-title"><i class="fas fa-microchip"></i> Device Configuration</h2>
                </div>
                <div class="card-content">
                    
                    <div id="forms-container">
                        
                        <div id="tab-device" class="settings-form-section active">
                            <div class="settings-description">
                                <i class="fas fa-info-circle"></i> <strong>Core Device Settings:</strong> Role determines power usage and mesh behavior.
                            </div>
                            <form id="form-device" onsubmit="saveForm(event, 'device')"></form>
                        </div>

                        <div id="tab-lora" class="settings-form-section">
                            <div class="settings-description">
                                <i class="fas fa-globe"></i> <strong>LoRa Configuration:</strong> Region MUST match your physical location to be legal.
                            </div>
                            <form id="form-lora" onsubmit="saveForm(event, 'lora')"></form>
                        </div>

                        <div id="tab-power" class="settings-form-section">
                            <div class="settings-description">
                                <i class="fas fa-battery-half"></i> <strong>Power Management:</strong> Configure sleep cycles and battery protection.
                            </div>
                            <form id="form-power" onsubmit="saveForm(event, 'power')"></form>
                        </div>

                        <div id="tab-position" class="settings-form-section">
                            <div class="settings-description">
                                <i class="fas fa-satellite"></i> <strong>GPS Settings:</strong> Location sharing and GPS hardware control (high battery usage).
                            </div>
                            <form id="form-position" onsubmit="saveForm(event, 'position')"></form>
                        </div>

                        <div id="tab-network" class="settings-form-section">
                            <div class="settings-description">
                                <i class="fas fa-wifi"></i> <strong>WiFi / Ethernet:</strong> For ESP32 devices. Enabling WiFi usually disables Bluetooth.
                            </div>
                            <form id="form-network" onsubmit="saveForm(event, 'network')"></form>
                        </div>

                        <div id="tab-display" class="settings-form-section">
                            <div class="settings-description">
                                <i class="fas fa-tv"></i> <strong>Display:</strong> OLED/E-Ink behavior, timeouts, and carousel settings.
                            </div>
                            <form id="form-display" onsubmit="saveForm(event, 'display')"></form>
                        </div>

                        <div id="tab-bluetooth" class="settings-form-section">
                            <div class="settings-description">
                                <i class="fab fa-bluetooth"></i> <strong>Bluetooth:</strong> Connection settings for the Meshtastic mobile app.
                            </div>
                            <form id="form-bluetooth" onsubmit="saveForm(event, 'bluetooth')"></form>
                        </div>

                        <div id="tab-security" class="settings-form-section">
                            <div class="settings-description">
                                <i class="fas fa-lock"></i> <strong>Access Control:</strong> Serial console locking and managed node keys.
                            </div>
                            <form id="form-security" onsubmit="saveForm(event, 'security')"></form>
                        </div>

                        <div id="tab-channels" class="settings-form-section">
                            <div class="settings-description">
                                <i class="fas fa-users"></i> <strong>Channels:</strong> Manage up to 8 channels. Index 0 is Primary. Scan QR codes to join.
                            </div>
                            <div id="channels-list"></div>
                            <div class="form-actions">
                                <button type="button" class="btn btn-primary" onclick="addChannel()"><i class="fas fa-plus"></i> Add New Channel</button>
                            </div>
                        </div>

                        <div id="tab-modules" class="settings-form-section">
                            <div class="settings-description">
                                <i class="fas fa-cubes"></i> <strong>Modules:</strong> MQTT, Telemetry, Serial, and other advanced features.
                            </div>
                            
                            <h3 style="color: var(--primary-color); border-bottom: 1px solid var(--border-color); padding-bottom: 10px; margin-bottom: 20px;">
                                <i class="fas fa-cloud"></i> MQTT Module
                            </h3>
                            <form id="form-mqtt" onsubmit="saveForm(event, 'mqtt')"></form>
                            
                            <h3 style="color: var(--primary-color); border-bottom: 1px solid var(--border-color); padding-bottom: 10px; margin: 40px 0 20px 0;">
                                <i class="fas fa-terminal"></i> Serial Module
                            </h3>
                            <form id="form-serial" onsubmit="saveForm(event, 'serial')"></form>
                            
                            <h3 style="color: var(--primary-color); border-bottom: 1px solid var(--border-color); padding-bottom: 10px; margin: 40px 0 20px 0;">
                                <i class="fas fa-chart-line"></i> Telemetry Module
                            </h3>
                            <form id="form-telemetry" onsubmit="saveForm(event, 'telemetry')"></form>
                        </div>

                        <div id="tab-actions" class="settings-form-section">
                            <div class="settings-description">
                                <i class="fas fa-bolt"></i> <strong>Maintenance:</strong> Backups, power control, and factory resets.
                            </div>
                            
                            <div class="channel-card-item">
                                <h3 style="margin-top: 0; color: var(--primary-color);"><i class="fas fa-archive"></i> Backup & Restore</h3>
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 15px;">
                                    <div>
                                        <p class="setting-help" style="margin-bottom: 15px;">Download complete device configuration (Channels + Settings) as JSON.</p>
                                        <button type="button" class="btn btn-success" onclick="exportConfig()" style="width: 100%; justify-content: center;"><i class="fas fa-download"></i> Export Config</button>
                                    </div>
                                    <div class="file-drop" onclick="document.getElementById('importFile').click()">
                                        <input type="file" id="importFile" hidden accept=".json" onchange="importConfig(this.files[0])">
                                        <i class="fas fa-file-import" style="font-size: 2rem; margin-bottom: 15px; color: var(--text-secondary);"></i>
                                        <div style="font-weight: 600;">Click to Import Config</div>
                                        <div class="setting-help">Warning: Overwrites all settings!</div>
                                    </div>
                                </div>
                            </div>

                            <div class="actions-grid">
                                <div class="action-box" onclick="rebootDevice()">
                                    <i class="fas fa-sync action-icon" style="color: var(--primary-color);"></i>
                                    <h3>Reboot</h3>
                                    <span class="setting-help">Restart the device</span>
                                </div>
                                <div class="action-box" onclick="shutdownDevice()">
                                    <i class="fas fa-power-off action-icon" style="color: var(--warning);"></i>
                                    <h3>Shutdown</h3>
                                    <span class="setting-help">Power off completely</span>
                                </div>
                                <div class="action-box" onclick="factoryReset()">
                                    <i class="fas fa-skull-crossbones action-icon" style="color: var(--danger);"></i>
                                    <h3 style="color: var(--danger);">Factory Reset</h3>
                                    <span class="setting-help">ERASE ALL DATA</span>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
    let CONFIG_DATA = null;

    document.addEventListener('DOMContentLoaded', () => {
        fetchSettings();
    });

    function switchTab(tabId) {
        document.querySelectorAll('.settings-nav-item').forEach(el => el.classList.remove('active'));
        event.currentTarget.classList.add('active');

        document.querySelectorAll('.settings-form-section').forEach(el => el.classList.remove('active'));
        document.getElementById(`tab-${tabId}`).classList.add('active');
        
        const icon = event.currentTarget.querySelector('i').className;
        const text = event.currentTarget.textContent.trim();
        document.getElementById('current-section-title').innerHTML = `<i class="${icon}"></i> ${text} Configuration`;
    }

    async function fetchSettings() {
        try {
            const response = await fetch('/');
            const html = await response.text();
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            
            // Extract data from backend (if passed via data attributes or script tags)
            // For now, we'll make a separate API call
            const dataResponse = await fetch('/api/config');
            CONFIG_DATA = await dataResponse.json();
            
            document.getElementById('node_name').textContent = CONFIG_DATA.node_name || 'Meshtastic Node';
            
            renderForm('device', CONFIG_DATA.Device);
            renderForm('lora', CONFIG_DATA.Radio);
            renderForm('power', CONFIG_DATA.Power);
            renderForm('position', CONFIG_DATA.Position);
            renderForm('network', CONFIG_DATA.Network);
            renderForm('display', CONFIG_DATA.Display);
            renderForm('bluetooth', CONFIG_DATA.Bluetooth);
            renderForm('security', CONFIG_DATA.Security);
            
            renderForm('mqtt', CONFIG_DATA.Modules?.MQTT);
            renderForm('serial', CONFIG_DATA.Modules?.Serial);
            renderForm('telemetry', CONFIG_DATA.Modules?.Telemetry);

            renderChannels(CONFIG_DATA.Channels);
        } catch (error) {
            console.error('Error fetching settings:', error);
        }
    }

    function renderForm(sectionId, data) {
        const form = document.getElementById(`form-${sectionId}`);
        if (!form || !data) return;
        
        form.innerHTML = '';

        for (const [key, fieldData] of Object.entries(data)) {
            if (key === 'type' || key === 'options' || key === 'description' || key === 'is_repeated') continue;
            
            const wrapper = document.createElement('div');
            wrapper.className = 'setting-item';
            
            const value = fieldData.value !== undefined ? fieldData.value : '';
            const fieldType = fieldData.type || 'string';
            const options = fieldData.options || null;
            
            let badge = '';
            let label = key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
            let help = fieldData.description || '';

            const left = `
                <div class="setting-info">
                    <div class="setting-label">${label} ${badge}</div>
                    <div class="setting-help">${help}</div>
                </div>
            `;

            let inputHtml = '';
            const fieldId = `${sectionId}_${key}`;

            if (options) {
                // Enum/Select field
                let opts = '';
                for (const [k, v] of Object.entries(options)) {
                    const selected = (String(value) === String(k)) ? 'selected' : '';
                    opts += `<option value="${k}" ${selected}>${v}</option>`;
                }
                inputHtml = `<select name="${key}">${opts}</select>`;
            } 
            else if (fieldType === 'bool') {
                const checked = value ? 'checked' : '';
                inputHtml = `
                    <div class="checkbox-wrapper">
                        <input type="checkbox" name="${key}" id="${fieldId}" ${checked} onchange="this.nextElementSibling.innerText = this.checked ? 'Enabled' : 'Disabled'">
                        <label for="${fieldId}">${value ? 'Enabled' : 'Disabled'}</label>
                    </div>`;
            }
            else if (fieldType === 'number' || fieldType === 'float') {
                const step = fieldType === 'float' ? '0.01' : '1';
                inputHtml = `<input type="number" step="${step}" name="${key}" value="${value}">`;
            }
            else if (fieldType === 'bytes') {
                inputHtml = `
                    <div class="input-with-actions">
                        <input type="text" name="${key}" value="${value}" id="inp_${fieldId}" placeholder="Base64 encoded">
                        <button type="button" class="input-action-btn" onclick="copyId('inp_${fieldId}')" title="Copy"><i class="fas fa-copy"></i></button>
                    </div>`;
            }
            else {
                // String or default
                inputHtml = `<input type="text" name="${key}" value="${value}">`;
            }

            wrapper.innerHTML = left + `<div class="setting-control">${inputHtml}</div>`;
            form.appendChild(wrapper);
        }

        const btnRow = document.createElement('div');
        btnRow.className = 'form-actions';
        btnRow.innerHTML = `<button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save ${sectionId.toUpperCase()} Config</button>`;
        form.appendChild(btnRow);
    }

    function renderChannels(channels) {
        const container = document.getElementById('channels-list');
        container.innerHTML = '';
        if (!channels) return;

        channels.forEach(ch => {
            const el = document.createElement('div');
            el.className = 'channel-card-item';
            
            let roleBadge = '';
            const roleMap = {0: 'DISABLED', 1: 'PRIMARY', 2: 'SECONDARY'};
            const roleName = roleMap[ch.role] || 'UNKNOWN';
            
            if (ch.role === 1) roleBadge = '<span class="badge badge-critical">PRIMARY</span>';
            else if (ch.role === 0) roleBadge = '<span class="badge badge-info">DISABLED</span>';
            else roleBadge = '<span class="badge badge-warning">SECONDARY</span>';

            let qrSection = '';
            if (ch.qr_code && ch.qr_code.img_base64) {
                qrSection = `
                <div class="qr-section">
                    <div class="qr-img">
                         <img src="data:image/png;base64,${ch.qr_code.img_base64}" alt="QR Code">
                    </div>
                    <div style="flex:1">
                        <h4 style="margin:0 0 10px 0; color:var(--primary-color);">Scan to Join "${ch.qr_code.name || `Channel ${ch.index}`}"</h4>
                        <p class="setting-help" style="margin-bottom:15px;">Scan with Meshtastic App to automatically configure this channel.</p>
                        <div class="input-with-actions">
                            <input type="text" value="${ch.qr_code.url || ''}" readonly id="qr_${ch.index}">
                            <button type="button" class="input-action-btn" onclick="copyId('qr_${ch.index}')"><i class="fas fa-copy"></i> Copy URL</button>
                        </div>
                    </div>
                </div>`;
            }

            const settings = ch.settings || {};
            const name = settings.name?.value || '';
            const psk = settings.psk?.value || '';
            const uplink = settings.uplink_enabled?.value || false;
            const downlink = settings.downlink_enabled?.value || false;

            // Generate role options
            let roleOptions = '';
            const roles = ch.role_options || {0: 'DISABLED', 1: 'PRIMARY', 2: 'SECONDARY'};
            for (const [k, v] of Object.entries(roles)) {
                const selected = (parseInt(k) === ch.role) ? 'selected' : '';
                roleOptions += `<option value="${k}" ${selected}>${v}</option>`;
            }

            el.innerHTML = `
                <div class="channel-header-row">
                    <h3 style="margin:0; display:flex; align-items:center; gap:10px;">
                        Channel ${ch.index} ${roleBadge}
                    </h3>
                    ${ch.index > 0 ? `<button type="button" class="btn btn-danger" style="padding:6px 12px; font-size:0.8rem;" onclick="deleteChannel(${ch.index})"><i class="fas fa-trash"></i></button>` : ''}
                </div>
                ${qrSection}
                <form onsubmit="saveChannel(event, ${ch.index})">
                    <input type="hidden" name="channel_index" value="${ch.index}">
                    
                    <div class="setting-item">
                        <div class="setting-info">
                            <div class="setting-label">Channel Role</div>
                            <div class="setting-help">PRIMARY (Index 0), SECONDARY, or DISABLED</div>
                        </div>
                        <select name="role">${roleOptions}</select>
                    </div>
                    
                    <div class="setting-item">
                        <div class="setting-info">
                            <div class="setting-label">Name</div>
                            <div class="setting-help">Display name (max 12 characters)</div>
                        </div>
                        <input type="text" name="name" value="${name}" maxlength="12">
                    </div>
                    
                    <div class="setting-item">
                        <div class="setting-info">
                            <div class="setting-label">Pre-Shared Key (PSK) <span class="badge badge-warning">Secret</span></div>
                            <div class="setting-help">AES256 Key (Base64 encoded). All nodes must use the same key.</div>
                        </div>
                        <div class="input-with-actions">
                            <input type="password" name="psk" value="${psk}" id="psk_${ch.index}">
                            <button type="button" class="input-action-btn" onclick="togglePassword('psk_${ch.index}')"><i class="fas fa-eye"></i></button>
                            <button type="button" class="input-action-btn" onclick="generatePSK('psk_${ch.index}')" title="Generate New Key"><i class="fas fa-random"></i></button>
                            <button type="button" class="input-action-btn" onclick="copyId('psk_${ch.index}')"><i class="fas fa-copy"></i></button>
                        </div>
                    </div>
                    
                    <div class="setting-item">
                        <div class="setting-info">
                            <div class="setting-label">Uplink Enabled</div>
                            <div class="setting-help">Allow transmitting on this channel</div>
                        </div>
                        <div class="checkbox-wrapper">
                            <input type="checkbox" name="uplink_enabled" id="up_${ch.index}" ${uplink ? 'checked' : ''}>
                            <label for="up_${ch.index}">${uplink ? 'Enabled' : 'Disabled'}</label>
                        </div>
                    </div>
                    
                    <div class="setting-item">
                        <div class="setting-info">
                            <div class="setting-label">Downlink Enabled</div>
                            <div class="setting-help">Allow receiving on this channel</div>
                        </div>
                        <div class="checkbox-wrapper">
                            <input type="checkbox" name="downlink_enabled" id="down_${ch.index}" ${downlink ? 'checked' : ''}>
                            <label for="down_${ch.index}">${downlink ? 'Enabled' : 'Disabled'}</label>
                        </div>
                    </div>
                    
                    <div class="form-actions">
                         <button type="submit" class="btn btn-success"><i class="fas fa-save"></i> Save Channel ${ch.index}</button>
                    </div>
                </form>
            `;
            container.appendChild(el);
        });
    }

    function toggleLoader(show) {
        const overlay = document.getElementById('loading-overlay');
        if(show) overlay.classList.add('active');
        else overlay.classList.remove('active');
    }

    async function saveForm(e, section) {
        e.preventDefault();
        toggleLoader(true);
        
        const formData = new FormData(e.target);
        
        // Add checkboxes that are unchecked
        e.target.querySelectorAll('input[type="checkbox"]').forEach(cb => {
            if (!formData.has(cb.name)) {
                formData.append(cb.name, 'false');
            }
        });

        try {
            const response = await fetch(`/save/LocalConfig/${section}`, {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            toggleLoader(false);
            
            if (result.status === 'success') {
                showMessage(result.message, 'success');
            } else {
                showMessage(result.message, 'error');
            }
        } catch (error) {
            toggleLoader(false);
            showMessage('Error saving configuration', 'error');
            console.error(error);
        }
    }

    async function saveChannel(e, index) {
        e.preventDefault();
        toggleLoader(true);
        
        const formData = new FormData(e.target);
        
        // Ensure channel_index is set
        if (!formData.has('channel_index')) {
            formData.append('channel_index', index);
        }
        
        // Add checkbox states
        e.target.querySelectorAll('input[type="checkbox"]').forEach(cb => {
            formData.set(cb.name, cb.checked ? 'true' : 'false');
        });

        try {
            const response = await fetch('/channel/save', {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            toggleLoader(false);
            
            if (result.status === 'success') {
                showMessage(result.message, 'success');
                // Refresh to get new QR code
                setTimeout(() => fetchSettings(), 1000);
            } else {
                showMessage(result.message, 'error');
            }
        } catch (error) {
            toggleLoader(false);
            showMessage('Error saving channel', 'error');
            console.error(error);
        }
    }

    function showMessage(msg, type) {
        const el = document.getElementById('status-message');
        el.innerHTML = msg;
        el.className = `status-message ${type}`;
        el.style.display = 'block';
        setTimeout(() => el.style.display = 'none', 4000);
    }

    function togglePassword(id) {
        const input = document.getElementById(id);
        if(!input) return;
        input.type = input.type === 'password' ? 'text' : 'password';
    }

    function copyId(id) {
        const input = document.getElementById(id);
        if(!input) return;
        input.select();
        document.execCommand('copy');
        showMessage('Copied to clipboard', 'success');
    }

    function generatePSK(id) {
        const array = new Uint8Array(32);
        window.crypto.getRandomValues(array);
        const key = btoa(String.fromCharCode.apply(null, array));
        const input = document.getElementById(id);
        input.value = key;
        input.type = 'text';
        showMessage('New AES256 Key Generated', 'success');
    }

    async function addChannel() {
        toggleLoader(true);
        try {
            const response = await fetch('/channel/add', { method: 'POST' });
            const result = await response.json();
            toggleLoader(false);
            
            if (result.status === 'success') {
                showMessage(result.message, 'success');
                fetchSettings();
            } else {
                showMessage(result.message, 'error');
            }
        } catch (error) {
            toggleLoader(false);
            showMessage('Error adding channel', 'error');
        }
    }
    
    async function deleteChannel(idx) {
        if(confirm(`Are you sure you want to delete Channel ${idx}?`)) {
            toggleLoader(true);
            try {
                const formData = new FormData();
                formData.append('index', idx);
                
                const response = await fetch('/channel/delete', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                toggleLoader(false);
                
                if (result.status === 'success') {
                    showMessage(result.message, 'success');
                    fetchSettings();
                } else {
                    showMessage(result.message, 'error');
                }
            } catch (error) {
                toggleLoader(false);
                showMessage('Error deleting channel', 'error');
            }
        }
    }

    async function exportConfig() {
        toggleLoader(true);
        try {
            const response = await fetch('/config/export');
            const blob = await response.blob();
            
            const url = window.URL.createObjectURL(blob);
            const anchor = document.createElement('a');
            anchor.href = url;
            anchor.download = `meshtastic-config-${new Date().toISOString().slice(0,10)}.json`;
            document.body.appendChild(anchor);
            anchor.click();
            anchor.remove();
            window.URL.revokeObjectURL(url);
            
            toggleLoader(false);
            showMessage('Configuration exported successfully', 'success');
        } catch (error) {
            toggleLoader(false);
            showMessage('Error exporting configuration', 'error');
        }
    }

    async function importConfig(file) {
        if(!file) return;
        if(confirm("⚠️ WARNING: This will overwrite ALL current settings. Continue?")) {
            toggleLoader(true);
            
            const formData = new FormData();
            formData.append('config_file', file);
            
            try {
                const response = await fetch('/config/import', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                toggleLoader(false);
                
                if (result.status === 'success') {
                    showMessage(result.message, 'success');
                } else {
                    showMessage(result.message, 'error');
                }
            } catch (error) {
                toggleLoader(false);
                showMessage('Error importing configuration', 'error');
            }
        }
    }

    async function rebootDevice() {
        if(confirm("Reboot device now?")) {
            toggleLoader(true);
            try {
                const response = await fetch('/device/reboot', { method: 'POST' });
                const result = await response.json();
                toggleLoader(false);
                showMessage(result.message, result.status === 'success' ? 'success' : 'error');
            } catch (error) {
                toggleLoader(false);
                showMessage('Error rebooting device', 'error');
            }
        }
    }

    async function shutdownDevice() {
        if(confirm("Shutdown device? You will need physical access to turn it back on.")) {
            toggleLoader(true);
            try {
                const response = await fetch('/device/shutdown', { method: 'POST' });
                const result = await response.json();
                toggleLoader(false);
                showMessage(result.message, result.status === 'success' ? 'success' : 'error');
            } catch (error) {
                toggleLoader(false);
                showMessage('Error shutting down device', 'error');
            }
        }
    }

    async function factoryReset() {
        const check1 = confirm("🚨 FACTORY RESET 🚨\n\nThis will erase ALL settings, channels, and encryption keys.");
        if(check1) {
            const check2 = confirm("Are you absolutely sure? This cannot be undone.");
            if(check2) {
                toggleLoader(true);
                try {
                    const response = await fetch('/device/factory-reset', { method: 'POST' });
                    const result = await response.json();
                    toggleLoader(false);
                    showMessage(result.message, 'error');
                } catch (error) {
                    toggleLoader(false);
                    showMessage('Error performing factory reset', 'error');
                }
            }
        }
    }
    </script>
</body>
</html>