<style>
    .acct-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;max-width:1400px;margin:0 auto;}
    .acct-full{grid-column:span 2;}
    @media(max-width:900px){.acct-grid{grid-template-columns:1fr;}.acct-full{grid-column:span 1;}}
    .acct-row{display:flex;justify-content:space-between;align-items:center;padding:10px 0;border-bottom:1px solid var(--bd);}
    .acct-row:last-child{border-bottom:none;}
    .acct-lbl{font-family:var(--mono);font-size:10px;color:var(--txt3);text-transform:uppercase;letter-spacing:1px;}
    .acct-val{font-family:var(--mono);font-size:13px;color:var(--txt);display:flex;align-items:center;gap:8px;}
    .badge{font-size:9px;padding:2px 8px;border-radius:3px;font-family:var(--mono);font-weight:700;text-transform:uppercase;}
    .badge-on{background:rgba(0,240,144,.1);color:var(--ok);border:1px solid rgba(0,240,144,.3);}
    .badge-off{background:rgba(255,48,80,.1);color:var(--err);border:1px solid rgba(255,48,80,.3);}
    .badge-warn{background:rgba(255,180,0,.1);color:#ffb400;border:1px solid rgba(255,180,0,.3);}
    .badge-info{background:rgba(0,200,245,.08);color:var(--acc);border:1px solid rgba(0,200,245,.3);}
    .alert{padding:12px;border-radius:4px;font-size:12px;font-family:var(--mono);margin-bottom:16px;display:flex;align-items:flex-start;gap:10px;}
    .alert-info{background:rgba(0,200,245,.06);border:1px solid rgba(0,200,245,.2);color:var(--acc);}
    .alert-ok{background:rgba(0,240,144,.06);border:1px solid rgba(0,240,144,.2);color:var(--ok);}
    .alert-err{background:rgba(255,48,80,.06);border:1px solid rgba(255,48,80,.2);color:var(--err);}
    .stat-box{flex:1;text-align:center;padding:12px;background:var(--bg);border:1px solid var(--bd2);border-radius:var(--r);}
    .stat-val{font-size:24px;font-weight:800;font-family:var(--mono);}
    .stat-lbl{font-size:9px;color:var(--txt3);text-transform:uppercase;letter-spacing:1px;margin-top:4px;}
    .stat-row{display:flex;gap:10px;margin-bottom:10px;}
    .guide-step{display:flex;gap:12px;margin-bottom:16px;}
    .guide-num{width:28px;height:28px;border-radius:50%;background:var(--acc-dim);color:var(--acc);display:flex;align-items:center;justify-content:center;font-weight:800;font-size:13px;flex-shrink:0;}
    .guide-txt{font-size:12px;color:var(--txt2);line-height:1.5;}
    .guide-txt strong{color:var(--txt);}
    .guide-txt p{margin:2px 0 0;color:var(--txt3);font-size:11px;}
    .qrc{text-align:center;padding:16px;}
    .qrc img{max-width:200px;border-radius:4px;border:2px solid var(--bd2);}
    .mk{font-family:var(--mono);font-size:11px;text-align:center;padding:8px;background:var(--bg);border:1px solid var(--bd2);border-radius:4px;cursor:pointer;word-break:break-all;}
    .ti{width:80px;text-align:center;font-family:var(--mono);font-size:18px;letter-spacing:4px;background:var(--bg);border:2px solid var(--bd2);color:var(--txt);padding:8px;border-radius:4px;outline:none;}
    .ti:focus{border-color:var(--acc);}
    .bc{font-family:var(--mono);font-size:13px;padding:8px 12px;background:var(--bg);border:1px solid var(--bd2);border-radius:4px;text-align:center;letter-spacing:1px;}
    .bcg{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin:12px 0;}
    .ut{width:100%;border-collapse:collapse;font-size:12px;}
    .ut th{text-align:left;padding:10px 12px;color:var(--txt3);font-size:10px;text-transform:uppercase;letter-spacing:1px;border-bottom:1px solid var(--bd2);font-weight:700;}
    .ut td{padding:10px 12px;border-bottom:1px solid var(--bd);}
    .ut tr:hover{background:var(--bg2);}
    .fr{display:flex;gap:12px;margin-bottom:12px;}
    .fc{flex:1;}
    .fc label{display:block;font-size:10px;color:var(--txt3);margin-bottom:4px;text-transform:uppercase;letter-spacing:1px;font-weight:700;}
    .login-bar{display:flex;gap:2px;height:40px;align-items:flex-end;}
    .login-bar-seg{flex:1;min-width:4px;border-radius:2px 2px 0 0;transition:opacity .2s;opacity:.7;}
    .login-bar-seg:hover{opacity:1;}
    .mbg{position:fixed;inset:0;background:rgba(0,0,0,.7);display:flex;align-items:center;justify-content:center;z-index:9999;}
    .mdl{background:var(--bg1);border:1px solid var(--bd2);border-radius:var(--r);padding:24px;max-width:400px;width:90%;}
    .mdl h3{margin:0 0 16px;font-size:14px;font-family:var(--mono);text-transform:uppercase;}
</style>

<div class="acct-grid">
    <!-- Header -->
    <div class="acct-full" style="margin-bottom:0;">
        <div style="display:flex;align-items:center;gap:12px;">
            <span style="font-size:16px;font-weight:800;color:var(--txt);letter-spacing:1px;">ACCOUNT & SECURITY</span>
            <span style="font-size:10px;color:var(--txt3);font-family:var(--mono);" id="page-subtitle">Loading account details...</span>
        </div>
    </div>

    <div id="mfa-alert-area" class="acct-full"></div>

    <!-- ═══ LEFT COLUMN: Profile + Access ═══ -->
    <div class="card">
        <div class="ch"><span class="ct"><span style="color:var(--acc);">⬡</span> YOUR PROFILE</span></div>
        <div class="cb">
            <div class="acct-row"><span class="acct-lbl">Username</span><span class="acct-val" id="p-user"><i class="fas fa-spinner fa-spin" style="color:var(--txt3);font-size:10px;"></i></span></div>
            <div class="acct-row"><span class="acct-lbl">Role</span><span class="acct-val" id="p-role">—</span></div>
            <div class="acct-row"><span class="acct-lbl">Account Created</span><span class="acct-val" id="p-created">—</span></div>
            <div class="acct-row"><span class="acct-lbl">Last Login</span><span class="acct-val" id="p-lastlogin">—</span></div>
            <div class="acct-row"><span class="acct-lbl">Total Logins</span><span class="acct-val" id="p-logincount">—</span></div>
            <div class="acct-row"><span class="acct-lbl">Account Status</span><span class="acct-val" id="p-status">—</span></div>
            <div style="padding-top:14px;">
                <button class="btn btn-err" onclick="if(confirm('Log out of MeshDash?')) window.location.href='/logout'" style="width:100%;justify-content:center;">
                    <i class="fas fa-right-from-bracket" style="margin-right:6px;"></i> LOG OUT
                </button>
            </div>
        </div>
    </div>

    <!-- ═══ RIGHT COLUMN: Dashboard Access ═══ -->
    <div class="card">
        <div class="ch"><span class="ct"><span style="color:var(--acc);">⬡</span> DASHBOARD ACCESS</span></div>
        <div class="cb">
            <div class="acct-row">
                <span class="acct-lbl">Public Mode</span>
                <span class="acct-val">
                    <span id="pm-status" class="badge badge-off">—</span>
                    <button class="btn btn-acc" id="pm-toggle" onclick="togglePublicMode()" style="display:none;font-size:10px;padding:4px 10px;">Toggle</button>
                </span>
            </div>
            <div class="acct-row">
                <span class="acct-lbl">Access Level</span>
                <span class="acct-val" id="pm-level">—</span>
            </div>
            <div style="padding:14px 0 0;font-size:11px;color:var(--txt3);line-height:1.6;">
                <div style="margin-bottom:8px;"><span class="badge badge-warn">ON</span> &nbsp; Dashboard accessible without login. Anyone on the network can view and control.</div>
                <div><span class="badge badge-on">OFF</span> &nbsp; Login required. Only authenticated users can access. <strong style="color:var(--ok);">Recommended.</strong></div>
            </div>
        </div>
    </div>

    <!-- ═══ MFA — left column ═══ -->
    <div class="card">
        <div class="ch"><span class="ct"><span style="color:var(--acc);">⬡</span> MULTI-FACTOR AUTH</span></div>
        <div class="cb">
            <div class="acct-row"><span class="acct-lbl">TOTP Status</span><span class="acct-val" id="mfa-status-badge"><i class="fas fa-spinner fa-spin" style="color:var(--txt3);font-size:10px;"></i></span></div>
            <div class="acct-row" id="mfa-backup-row" style="display:none;"><span class="acct-lbl">Backup Codes</span><span class="acct-val" id="mfa-backup-count">—</span></div>
            <div style="padding-top:14px;display:flex;gap:8px;">
                <button class="btn btn-acc" id="mfa-enable-btn" style="display:none;" onclick="startMfaSetup()"><i class="fas fa-plus" style="margin-right:5px;"></i> Enable MFA</button>
                <button class="btn btn-err" id="mfa-disable-btn" style="display:none;" onclick="showDisableFlow()"><i class="fas fa-trash" style="margin-right:5px;"></i> Disable</button>
            </div>
        </div>
    </div>

    <!-- ═══ MFA Guide — right column ═══ -->
    <div class="card" id="mfa-guide" style="display:none;">
        <div class="ch"><span class="ct"><span style="color:var(--acc);">⬡</span> HOW TO ENABLE MFA</span></div>
        <div class="cb">
            <p style="font-size:11px;color:var(--txt2);margin:0 0 14px;line-height:1.6;">Add an extra layer of security. Even if someone gets your password, they can't access your account without your authenticator device.</p>
            <div class="guide-step"><div class="guide-num">1</div><div class="guide-txt"><strong>Install an Authenticator App</strong><p>Google Authenticator, Authy, or Microsoft Authenticator. Any TOTP app works.</p></div></div>
            <div class="guide-step"><div class="guide-num">2</div><div class="guide-txt"><strong>Click "Enable MFA"</strong><p>Scan the QR code with your app, or enter the manual key.</p></div></div>
            <div class="guide-step"><div class="guide-num">3</div><div class="guide-txt"><strong>Enter the 6-Digit Code</strong><p>Enter the current code from your authenticator to confirm.</p></div></div>
            <div class="guide-step"><div class="guide-num">4</div><div class="guide-txt"><strong>Save Backup Codes</strong><p>8 one-time codes. Store safely — your only way back in if you lose your device.</p></div></div>
        </div>
    </div>

    <!-- MFA Setup Flow — full width -->
    <div id="mfa-setup-flow" class="card acct-full" style="display:none;">
        <div class="ch"><span class="ct"><span style="color:var(--acc);">⬡</span> MFA SETUP</span></div>
        <div class="cb">
            <div id="mfa-step-qr">
                <p style="font-size:12px;color:var(--txt2);margin:0 0 12px;">Scan this QR code with your authenticator app.</p>
                <div class="qrc"><img id="mfa-qr-img" src="" alt="QR"></div>
                <p style="font-size:10px;color:var(--txt3);text-align:center;margin:8px 0 4px;">Or enter manually:</p>
                <div class="mk" id="mfa-manual-key" onclick="navigator.clipboard.writeText(this.textContent).then(()=>{this.style.borderColor='var(--ok)';setTimeout(()=>this.style.borderColor='var(--bd2)',1500);})" title="Click to copy"></div>
                <div style="text-align:center;margin-top:16px;">
                    <p style="font-size:11px;color:var(--txt2);margin:0 0 10px;">Enter the 6-digit code to confirm:</p>
                    <div style="display:flex;align-items:center;justify-content:center;gap:10px;">
                        <input type="text" id="mfa-confirm-code" class="ti" maxlength="6" inputmode="numeric" placeholder="000000">
                        <button class="btn btn-acc" id="mfa-confirm-btn" onclick="confirmMfa()"><i class="fas fa-check" style="margin-right:5px;"></i> Confirm</button>
                    </div>
                </div>
            </div>
            <div id="mfa-step-codes" style="display:none;">
                <div class="alert alert-ok"><i class="fas fa-circle-check"></i><div>MFA enabled. Save these backup codes — they will not be shown again.</div></div>
                <div class="bcg" id="mfa-codes-grid"></div>
                <div style="text-align:center;margin-top:12px;">
                    <button class="btn btn-acc" onclick="copyBackupCodes()"><i class="fas fa-copy" style="margin-right:5px;"></i> Copy All</button>
                    <button class="btn btn-ok" onclick="closeMfaSetup()" style="margin-left:8px;"><i class="fas fa-check" style="margin-right:5px;"></i> Done</button>
                </div>
            </div>
            <div style="text-align:center;margin-top:12px;"><a href="#" onclick="cancelMfaSetup();return false;" style="color:var(--txt3);font-size:10px;font-family:var(--mono);text-decoration:none;" id="mfa-cancel-link"><i class="fas fa-times"></i> Cancel</a></div>
        </div>
    </div>

    <!-- MFA Disable — full width -->
    <div id="mfa-disable-flow" class="card acct-full" style="display:none;">
        <div class="ch" style="color:var(--err);"><span class="ct"><span style="color:var(--err);">⬡</span> DISABLE MFA</span></div>
        <div class="cb">
            <p style="font-size:12px;color:var(--txt2);margin:0 0 8px;">Enter your password to confirm.</p>
            <input type="password" id="mfa-disable-password" class="inp inp-mono" placeholder="Enter password" autocomplete="current-password" style="max-width:300px;">
            <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:10px;">
                <button class="btn" onclick="cancelDisable()">Cancel</button>
                <button class="btn btn-err" id="mfa-disable-confirm-btn" onclick="confirmDisable()"><i class="fas fa-trash" style="margin-right:5px;"></i> Disable</button>
            </div>
        </div>
    </div>

    <!-- ═══ ADMIN: System Overview — full width ═══ -->
    <div id="admin-stats-section" class="acct-full" style="display:none;">
        <div class="card">
            <div class="ch"><span class="ct"><span style="color:var(--acc);">⬡</span> SYSTEM OVERVIEW</span></div>
            <div class="cb">
                <div class="stat-row">
                    <div class="stat-box"><div class="stat-val" id="s-total" style="color:var(--acc);">—</div><div class="stat-lbl">Total Users</div></div>
                    <div class="stat-box"><div class="stat-val" id="s-active" style="color:var(--ok);">—</div><div class="stat-lbl">Active</div></div>
                    <div class="stat-box"><div class="stat-val" id="s-suspended" style="color:var(--err);">—</div><div class="stat-lbl">Suspended</div></div>
                    <div class="stat-box"><div class="stat-val" id="s-mfa" style="color:var(--acc);">—</div><div class="stat-lbl">MFA Enabled</div></div>
                </div>
                <div class="stat-row">
                    <div class="stat-box"><div class="stat-val" id="s-admins" style="color:var(--ok);">—</div><div class="stat-lbl">Admins</div></div>
                    <div class="stat-box"><div class="stat-val" id="s-operators" style="color:var(--acc);">—</div><div class="stat-lbl">Operators</div></div>
                    <div class="stat-box"><div class="stat-val" id="s-spectators" style="color:var(--txt3);">—</div><div class="stat-lbl">Spectators</div></div>
                    <div class="stat-box"><div class="stat-val" id="s-logins" style="color:var(--acc);">—</div><div class="stat-lbl">Total Logins</div></div>
                </div>
                <div style="margin-top:8px;">
                    <p style="font-family:var(--mono);font-size:10px;color:var(--txt3);margin:0 0 6px;text-transform:uppercase;">Login Activity (per user)</p>
                    <div class="login-bar" id="login-bar"></div>
                    <div id="login-bar-labels" style="display:flex;gap:2px;margin-top:4px;"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══ ADMIN: User Management — full width ═══ -->
    <div id="user-mgmt-section" class="acct-full" style="display:none;">
        <div class="card">
            <div class="ch">
                <span class="ct"><span style="color:var(--acc);">⬡</span> USER MANAGEMENT</span>
                <button class="btn btn-acc" onclick="toggleCreatePanel()" style="margin-left:auto;font-size:10px;padding:5px 12px;"><i class="fas fa-user-plus" style="margin-right:5px;"></i> New User</button>
            </div>
            <div class="cb" style="padding:0;">
                <div id="create-user-panel" style="display:none;padding:16px;border-bottom:1px solid var(--bd2);background:var(--bg2);">
                    <p style="font-family:var(--mono);font-size:11px;color:var(--acc);margin:0 0 12px;text-transform:uppercase;"><i class="fas fa-user-plus"></i> Create New User</p>
                    <div class="fr">
                        <div class="fc"><label>Username</label><input type="text" id="new-username" class="inp inp-mono" placeholder="operator_name" autocomplete="off"></div>
                        <div class="fc"><label>Role</label>
                            <select id="new-role" class="inp" style="width:100%;">
                                <option value="0">Admin — Full system access</option>
                                <option value="1" selected>Operator — Standard access</option>
                                <option value="2">Spectator — Read-only</option>
                            </select>
                        </div>
                    </div>
                    <div class="fr">
                        <div class="fc" style="flex:2;"><label>Password</label>
                            <div style="display:flex;gap:6px;">
                                <input type="text" id="new-password" class="inp inp-mono" placeholder="Min. 6 characters" autocomplete="new-password">
                                <button class="btn btn-acc" onclick="generatePassword()" style="white-space:nowrap;font-size:10px;"><i class="fas fa-dice"></i></button>
                            </div>
                        </div>
                        <div class="fc" style="flex:0 0 auto;"><label>Security</label>
                            <label style="display:flex;align-items:center;gap:6px;cursor:pointer;text-transform:none;font-size:12px;color:var(--txt);"><input type="checkbox" id="new-force-mfa"> Require MFA</label>
                        </div>
                    </div>
                    <div style="display:flex;gap:8px;justify-content:flex-end;">
                        <button class="btn" onclick="toggleCreatePanel()">Cancel</button>
                        <button class="btn btn-acc" id="create-user-btn" onclick="createUser()"><i class="fas fa-check" style="margin-right:5px;"></i> Create</button>
                    </div>
                    <div id="create-user-result" style="margin-top:10px;"></div>
                </div>
                <div style="overflow-x:auto;">
                    <table class="ut">
                        <thead><tr><th>User</th><th>Role</th><th>MFA</th><th>Status</th><th>Last Login</th><th>Logins</th><th style="text-align:right;">Actions</th></tr></thead>
                        <tbody id="users-tbody"><tr><td colspan="7" style="text-align:center;color:var(--txt3);padding:20px;"><i class="fas fa-spinner fa-spin"></i></td></tr></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="mbg" id="acct-modal" style="display:none;">
    <div class="mdl">
        <h3 id="modal-title">Confirm</h3>
        <p id="modal-body" style="font-size:13px;color:var(--txt2);margin:0 0 16px;"></p>
        <div id="modal-input-area"></div>
        <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:16px;">
            <button class="btn" onclick="closeModal()">Cancel</button>
            <button class="btn btn-acc" id="modal-confirm-btn">Confirm</button>
        </div>
    </div>
</div>

<script>
(function(){
    function sa(t,m){const a=document.getElementById('mfa-alert-area');const c=t==='error'?'alert-err':t==='ok'?'alert-ok':'alert-info';const i=t==='error'?'fa-triangle-exclamation':t==='ok'?'fa-circle-check':'fa-circle-info';a.innerHTML=`<div class="alert ${c}"><i class="fas ${i}"></i><span>${m}</span></div>`;setTimeout(()=>a.innerHTML='',10000);}
    function esc(s){return s?String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'):'';}

    async function loadProfile(){
        try{
            const r=await fetch('/api/account/me');
            if(!r.ok){document.getElementById('page-subtitle').textContent='Session expired — please log out and back in.';return;}
            const d=await r.json();
            document.getElementById('p-user').textContent=d.username||'—';
            document.getElementById('p-role').innerHTML=d.role!==undefined?['<span class="badge badge-on">ADMIN</span>','<span class="badge badge-info">OPERATOR</span>','<span class="badge badge-off">SPECTATOR</span>'][d.role]||'—':'—';
            document.getElementById('p-created').textContent=d.created_at?new Date(d.created_at).toLocaleDateString():'—';
            document.getElementById('p-lastlogin').textContent=d.last_login?new Date(d.last_login).toLocaleString():'First session';
            document.getElementById('p-logincount').textContent=d.login_count||0;
            document.getElementById('p-status').innerHTML=d.disabled?'<span class="badge badge-off">SUSPENDED</span>':'<span class="badge badge-on">ACTIVE</span>';
            document.getElementById('page-subtitle').textContent=`Signed in as ${d.username||'—'} · ${['Admin','Operator','Spectator'][d.role]||'—'}`;
            if(d.role===0){document.getElementById('admin-stats-section').style.display='';document.getElementById('user-mgmt-section').style.display='';}
        }catch(e){document.getElementById('page-subtitle').textContent='Could not load profile.';}
    }

    async function loadStatus(){
        try{
            const r=await fetch('/api/totp/status');
            if(!r.ok)return;
            const d=await r.json();
            const el=document.getElementById('mfa-status-badge');
            if(d.enabled){
                el.innerHTML='<span class="badge badge-on">ENABLED</span>';
                document.getElementById('mfa-disable-btn').style.display='';
                document.getElementById('mfa-enable-btn').style.display='none';
                document.getElementById('mfa-guide').style.display='none';
                if(d.backup_codes_remaining!==undefined){
                    document.getElementById('mfa-backup-row').style.display='';
                    document.getElementById('mfa-backup-count').innerHTML=`<span class="badge ${d.backup_codes_remaining>0?'badge-on':'badge-off'}">${d.backup_codes_remaining} remaining</span>`;
                }
            }else{
                el.innerHTML='<span class="badge badge-off">DISABLED</span>';
                document.getElementById('mfa-enable-btn').style.display='';
                document.getElementById('mfa-disable-btn').style.display='none';
                document.getElementById('mfa-guide').style.display='';
            }
        }catch(e){}
    }

    async function loadUsers(){
        try{
            const r=await fetch('/api/users');
            if(!r.ok)return;
            const d2=await r.json();
            const users=d2.users||d2;
            const tb=document.getElementById('users-tbody');
            if(!users.length){tb.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--txt3);padding:20px;">No users found.</td></tr>';return;}
            tb.innerHTML=users.map(u=>`<tr>
                <td><strong>${esc(u.username)}</strong></td>
                <td>${['<span class="badge badge-on">ADMIN</span>','<span class="badge badge-info">OPERATOR</span>','<span class="badge badge-off">SPECTATOR</span>'][u.role]||'—'}</td>
                <td>${u.totp_enabled?'<span class="badge badge-on">ON</span>':'<span class="badge badge-off">OFF</span>'}</td>
                <td>${u.disabled?'<span class="badge badge-off">SUSPENDED</span>':'<span class="badge badge-on">ACTIVE</span>'}</td>
                <td style="font-size:11px;color:var(--txt3);">${u.last_login?new Date(u.last_login).toLocaleDateString():'—'}</td>
                <td>${u.login_count||0}</td>
                <td style="text-align:right;white-space:nowrap;">
                    <button class="btn" style="font-size:9px;padding:3px 8px;" onclick="window.resetUserPassword('${esc(u.username)}')"><i class="fas fa-key"></i></button>
                    ${!u.disabled?`<button class="btn" style="font-size:9px;padding:3px 8px;" onclick="window.toggleUserSuspend('${esc(u.username)}',true)"><i class="fas fa-ban"></i></button>`:`<button class="btn btn-acc" style="font-size:9px;padding:3px 8px;" onclick="window.toggleUserSuspend('${esc(u.username)}',false)"><i class="fas fa-check"></i></button>`}
                    ${u.role!==0?`<button class="btn btn-err" style="font-size:9px;padding:3px 8px;" onclick="window.deleteUser('${esc(u.username)}')"><i class="fas fa-trash"></i></button>`:''}
                </td></tr>`).join('');
            // Login activity bar
            const bar=document.getElementById('login-bar');
            const labels=document.getElementById('login-bar-labels');
            const max=Math.max(...users.map(u=>u.login_count||0),1);
            bar.innerHTML=users.map(u=>{const h=Math.max(2,(u.login_count||0)/max*38);const col=u.role===0?'var(--ok)':u.role===1?'var(--acc)':'var(--txt3)';return `<div class="login-bar-seg" style="height:${h}px;background:${col};" title="${esc(u.username)}: ${u.login_count||0} logins"></div>`;}).join('');
            labels.innerHTML=users.map(u=>`<div style="flex:1;min-width:4px;font-family:var(--mono);font-size:7px;color:var(--txt3);text-align:center;overflow:hidden;white-space:nowrap;">${esc(u.username).substring(0,3)}</div>`).join('');

            // Populate system overview stats
            document.getElementById('s-total').textContent=users.length;
            document.getElementById('s-active').textContent=users.filter(u=>!u.disabled).length;
            document.getElementById('s-suspended').textContent=users.filter(u=>u.disabled).length;
            document.getElementById('s-mfa').textContent=users.filter(u=>u.totp_enabled).length;
            document.getElementById('s-admins').textContent=users.filter(u=>u.role===0).length;
            document.getElementById('s-operators').textContent=users.filter(u=>u.role===1).length;
            document.getElementById('s-spectators').textContent=users.filter(u=>u.role===2).length;
            document.getElementById('s-logins').textContent=users.reduce((s,u)=>s+(u.login_count||0),0);
        }catch(e){}
    }

    async function loadPublicMode(){
        try{
            const r=await fetch('/api/system/config');
            const d=await r.json();
            const pm=d.PUBLIC_MODE;
            const el=document.getElementById('pm-status');
            const btn=document.getElementById('pm-toggle');
            const lvl=document.getElementById('pm-level');
            if(pm){
                el.className='badge badge-warn';el.textContent='ON';
                btn.textContent='Disable';btn.style.display='';
                lvl.innerHTML='<span class="badge badge-warn">PUBLIC</span> No login required';
            }else{
                el.className='badge badge-on';el.textContent='OFF';
                btn.textContent='Enable';btn.style.display='';
                lvl.innerHTML='<span class="badge badge-on">SECURED</span> Login required';
            }
        }catch(e){}
    }

    async function togglePublicMode(){
        try{
            const r=await fetch('/api/system/config');
            const d=await r.json();
            const current=d.PUBLIC_MODE;
            if(!confirm(current?'Disable Public Mode? Login will be required after restart.':'Enable Public Mode? Dashboard will be accessible without login.'))return;
            const r2=await fetch('/api/system/config',{
                method:'POST',
                headers:{'Content-Type':'application/json','X-CSRF-Token':window._csrfToken||''},
                body:JSON.stringify({PUBLIC_MODE:!current})
            });
            if(r2.ok){
                alert('Public Mode '+(current?'disabled':'enabled')+'. Restart required to apply. Click OK to restart now.');
                fetch('/api/system/restart',{method:'POST',headers:{'X-CSRF-Token':window._csrfToken||''}}).catch(()=>{});
                setTimeout(()=>{setInterval(async()=>{try{const r=await fetch('/api/status');if(r.ok)window.location.reload();}catch(e){}},2000);},3000);
            }else{alert('Failed to toggle Public Mode.');}
        }catch(e){alert('Error: '+e);}
    }

    // MFA Setup
    let _bcc=[];
    function startMfaSetup(){document.getElementById('mfa-setup-flow').style.display='';document.getElementById('mfa-step-qr').style.display='';document.getElementById('mfa-step-codes').style.display='none';fetch('/api/totp/setup',{method:'POST',headers:{'X-CSRF-Token':window._csrfToken||''}}).then(r=>r.json()).then(d=>{document.getElementById('mfa-qr-img').src=d.qr_data_uri||'';document.getElementById('mfa-manual-key').textContent=d.secret||'';});}
    function cancelMfaSetup(){document.getElementById('mfa-setup-flow').style.display='none';}
    function closeMfaSetup(){document.getElementById('mfa-setup-flow').style.display='none';_bcc=[];loadStatus();loadProfile();}
    async function confirmMfa(){const code=document.getElementById('mfa-confirm-code').value.trim();if(!code||code.length!==6){sa('error','Enter 6 digits.');return;}try{const fd=new FormData();fd.append('code',code);const r=await fetch('/api/totp/confirm',{method:'POST',body:fd});const d=await r.json();if(!r.ok)throw new Error(d.detail||'Failed');_bcc=d.backup_codes||[];document.getElementById('mfa-step-qr').style.display='none';document.getElementById('mfa-step-codes').style.display='';document.getElementById('mfa-codes-grid').innerHTML=_bcc.map(c=>`<div class="bc">${c}</div>`).join('');sa('ok','MFA enabled successfully.');}catch(e){sa('error',e.message);}}
    function copyBackupCodes(){navigator.clipboard.writeText(_bcc.join('\\n'));sa('ok','Backup codes copied.');}
    function showDisableFlow(){document.getElementById('mfa-disable-flow').style.display='';}
    function cancelDisable(){document.getElementById('mfa-disable-flow').style.display='none';}
    async function confirmDisable(){const pw=document.getElementById('mfa-disable-password').value.trim();if(!pw){sa('error','Enter password.');return;}try{const fd=new FormData();fd.append('password',pw);const r=await fetch('/api/totp/disable',{method:'POST',body:fd});const d=await r.json();if(!r.ok)throw new Error(d.detail||'Failed');document.getElementById('mfa-disable-flow').style.display='none';sa('ok','MFA disabled.');loadStatus();loadProfile();}catch(e){sa('error',e.message);}}
    document.getElementById('mfa-disable-password')?.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();confirmDisable();}});

    // User Management
    function toggleCreatePanel(){const p=document.getElementById('create-user-panel');p.style.display=p.style.display==='none'?'':'none';}
    function generatePassword(){const chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%';let p='';for(let i=0;i<16;i++)p+=chars[Math.floor(Math.random()*chars.length)];document.getElementById('new-password').value=p;}
    async function createUser(){const un=document.getElementById('new-username').value.trim();const pw=document.getElementById('new-password').value.trim();const role=document.getElementById('new-role').value;const fm=document.getElementById('new-force-mfa').checked;if(!un||!pw){sa('error','Username and password required.');return;}if(pw.length<6){sa('error','Password min 6 chars.');return;}try{const r=await fetch('/api/users',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':window._csrfToken||''},body:JSON.stringify({username:un,password:pw,role:parseInt(role),force_mfa:fm})});const d=await r.json();if(!r.ok)throw new Error(d.detail||'Failed');document.getElementById('create-user-result').innerHTML=`<div class="alert alert-ok" style="margin:0;"><i class="fas fa-circle-check"></i><div><strong>${esc(un)}</strong> created as <strong>${d.role_label}</strong>.${fm?' MFA required on first login.':''}<br><span style="color:var(--txt2);font-size:10px;">Credentials: <strong>${esc(un)}</strong> / <strong>${esc(pw)}</strong></span></div></div>`;loadUsers();}catch(e){sa('error',e.message);}}
    window.resetUserPassword=function(u){openModal('Reset Password',`New password for <strong>${esc(u)}</strong>:`,'bt-p','<i class="fas fa-key"></i> Reset',`<div style="display:flex;gap:6px;"><input type="text" id="modal-pw" class="inp inp-mono" placeholder="Min 6 chars"><button class="btn btn-acc" onclick="fetch('/api/users/generate-password',{method:'POST',headers:{'X-CSRF-Token':window._csrfToken||''}}).then(r=>r.json()).then(d=>{document.getElementById('modal-pw').value=d.password;})" style="white-space:nowrap;"><i class="fas fa-dice"></i></button></div>`,async()=>{const pw=document.getElementById('modal-pw').value.trim();if(!pw||pw.length<6){sa('error','Min 6 chars.');return;}try{const r=await fetch(`/api/users/${encodeURIComponent(u)}/password`,{method:'PUT',headers:{'Content-Type':'application/json','X-CSRF-Token':window._csrfToken||''},body:JSON.stringify({password:pw})});if(!r.ok){const d=await r.json();throw new Error(d.detail);}closeModal();sa('ok',`Password reset for ${u}. New: ${pw}`);}catch(e){sa('error',e.message);closeModal();}});};
    window.toggleUserSuspend=function(u,suspend){openModal(suspend?'Suspend User':'Reactivate User',`Are you sure you want to ${suspend?'suspend':'reactivate'} <strong>${esc(u)}</strong>?`,'bt-d','<i class="fas fa-check"></i> Confirm',null,async()=>{try{const r=await fetch(`/api/users/${encodeURIComponent(u)}/status`,{method:'PUT',headers:{'Content-Type':'application/json','X-CSRF-Token':window._csrfToken||''},body:JSON.stringify({is_active:!suspend})});if(!r.ok)throw new Error('Failed');closeModal();sa('ok',`${u} ${suspend?'suspended':'reactivated'}.`);loadUsers();}catch(e){sa('error',e.message);closeModal();}});};
    window.deleteUser=function(u){openModal('Delete User',`Permanently delete <strong>${esc(u)}</strong>? This cannot be undone.`,'bt-d','<i class="fas fa-trash"></i> Delete',null,async()=>{try{const r=await fetch(`/api/users/${encodeURIComponent(u)}`,{method:'DELETE',headers:{'X-CSRF-Token':window._csrfToken||''}});if(!r.ok)throw new Error('Failed');closeModal();sa('ok',`${u} deleted.`);loadUsers();}catch(e){sa('error',e.message);closeModal();}});};

    // Modal
    function openModal(title,body,btnClass,btnHtml,inputArea,onConfirm){document.getElementById('modal-title').textContent=title;document.getElementById('modal-body').innerHTML=body;document.getElementById('modal-input-area').innerHTML=inputArea||'';const btn=document.getElementById('modal-confirm-btn');btn.className='btn '+(btnClass==='bt-d'?'btn-err':'btn-acc');btn.innerHTML=btnHtml;btn.onclick=onConfirm;document.getElementById('acct-modal').style.display='';}
    function closeModal(){document.getElementById('acct-modal').style.display='none';}
    window.closeModal=closeModal;

    window.AccountPageInit=function(){loadProfile();loadStatus();loadUsers();loadPublicMode();};
    loadProfile();loadStatus();loadUsers();loadPublicMode();
})();
</script>