/**
 * Flynn SPA Router
 *
 * Hash-based routing with page lifecycle management.
 * Drives both desktop sidebar and mobile pill navigation.
 */
import { getClient } from './lib/ws-client.js';
import { registerPwaServiceWorker } from './lib/pwa.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() {
  return window.location.hash.slice(1) || '/';
}

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

  if (!page) {
    contentEl.innerHTML = '<div class="p-8 text-center text-zinc-500">Page not found</div>';
    return;
  }

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

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

  // Update mobile pill active state
  document.querySelectorAll('.page-pill').forEach(pill => {
    pill.classList.toggle('active', pill.dataset.hash === `#${path}`);
  });

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

  const pageEl = document.createElement('div');
  pageEl.className = 'page max-w-7xl mx-auto px-4 md:px-0';
  contentEl.appendChild(pageEl);

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

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

  // Wire mobile pill click handlers
  document.querySelectorAll('.page-pill').forEach(pill => {
    pill.addEventListener('click', () => {
      window.location.hash = pill.dataset.hash;
    });
  });

  void registerPwaServiceWorker().catch(() => undefined);
  render();
}

// Connection status indicator — updates both desktop and mobile dots
export function initStatusIndicator() {
  const connDot = document.getElementById('conn-dot');
  const connText = document.getElementById('conn-text');
  const connDotMobile = document.getElementById('conn-dot-mobile');
  const client = getClient();

  const textMap = {
    connected: 'Connected',
    connecting: 'Connecting...',
    disconnected: 'Disconnected',
    locked: 'Locked',
  };

  const colorMap = {
    connected: 'bg-green-500',
    connecting: 'bg-amber-500',
    disconnected: 'bg-red-500',
    locked: 'bg-red-500',
  };

  const baseDotClasses = 'w-2 h-2 rounded-full shrink-0';

  function applyStatus(status) {
    const text = textMap[status] || 'Disconnected';
    const color = colorMap[status] || 'bg-zinc-600';

    if (connText) {
      connText.textContent = text;
    }
    if (connDot) {
      connDot.className = `${baseDotClasses} ${color}`;
    }
    if (connDotMobile) {
      connDotMobile.className = `${baseDotClasses} ${color}`;
    }
  }

  client.onStatusChange((status) => {
    applyStatus(status);
  });

  // Set initial status
  applyStatus(client.status);
}
