import { apiPost } from '../api.js';
import { esc } from './utils.js';

/**
 * @param {string} [activeNav] 'start' | 'machines' | 'tickets' | 'options' | 'users'
 */
export function updateNav(st, activeNav = '') {
  const nav = document.getElementById('main-nav');
  if (!nav) return;
  if (!st.loggedIn) {
    nav.innerHTML = '';
    return;
  }
  const isAdmin = st.user?.role === 'admin';
  const na = (key) => (activeNav === key ? 'nav-active' : '');
  nav.innerHTML = `
    <a href="/start.html" class="${na('start')}">Start</a>
    <a href="/machines.html" class="${na('machines')}">Maschinen</a>
    <a href="/tickets.html" class="${na('tickets')}">Tickets</a>
    ${
      isAdmin
        ? `<a href="/options.html" class="${na('options')}">Optionen</a><a href="/users.html" class="${na('users')}">Benutzer</a>`
        : ''
    }
    <span class="nav-user muted">${esc(st.user.username)}</span>
    <button type="button" class="secondary btn-nav-logout" id="btn-logout">Abmelden</button>`;
  const btn = document.getElementById('btn-logout');
  if (btn) {
    btn.onclick = async () => {
      try {
        await apiPost('/auth/logout', {});
      } catch {
        /* ignore */
      }
      updateNav({ loggedIn: false });
      location.href = '/login.html';
    };
  }
}
