/**
 * Flynn SPA Router
 *
 * Hash-based routing with page lifecycle management.
 */
import { getClient } from './lib/ws-client.js';

const routes = new Map();
let currentPage = null;
let contentEl = null;

export function registerPage(path, page) {
  routes.set(path, page);
}

export function navigate(path) {
  window.location.hash = path;
}

function getPath() {
  const hash = window.location.hash.slice(1) || '/';
  return hash;
}

async function render() {
  const path = getPath();
  const page = routes.get(path);

  if (!page) {
    contentEl.innerHTML = '<div class="page-error"><h2>Page not found</h2></div>';
    return;
  }

  // Teardown previous page
  if (currentPage?.teardown) {
    currentPage.teardown();
  }

  // Update nav
  document.querySelectorAll('.nav-link').forEach(link => {
    link.classList.toggle('active', link.getAttribute('href') === `#${path}`);
  });

  // Render new page
  currentPage = page;
  contentEl.innerHTML = '';

  const pageEl = document.createElement('div');
  pageEl.className = 'page';
  contentEl.appendChild(pageEl);

  await page.render(pageEl, getClient());
}

export function initRouter() {
  contentEl = document.getElementById('content');
  window.addEventListener('hashchange', render);
  render();
}

// Connection status indicator
export function initStatusIndicator() {
  const statusEl = document.getElementById('conn-status');
  const client = getClient();

  client.onStatusChange((status) => {
    statusEl.textContent = status === 'connected' ? 'Connected' :
      status === 'connecting' ? 'Connecting...' : 'Disconnected';
    statusEl.className = `conn-status ${status}`;
  });

  // Set initial status
  statusEl.textContent = client.status === 'connected' ? 'Connected' :
    client.status === 'connecting' ? 'Connecting...' : 'Disconnected';
  statusEl.className = `conn-status ${client.status}`;
}
