/**
 * router.mjs — Simple view router mapping dock items to view panels
 */

import store from './store.mjs';
import { $ } from './utils/dom.mjs';

const VIEWS = ['chat', 'activity', 'skills', 'knowledge', 'workspaces', 'settings'];

class Router {
  constructor() {
    this._initialized = false;
  }

  init() {
    if (this._initialized) return;
    this._initialized = true;

    // Subscribe to store view changes
    store.subscribe(
      (state) => state.ui.currentView,
      (view) => this._activateView(view)
    );

    // Apply initial view
    this._activateView(store.getState().ui.currentView);
  }

  navigate(viewId) {
    if (!VIEWS.includes(viewId)) {
      console.warn(`[router] Unknown view: ${viewId}`);
      return;
    }
    store.dispatch('SET_VIEW', viewId);
  }

  getViews() {
    return [...VIEWS];
  }

  getCurrentView() {
    return store.getState().ui.currentView;
  }

  _activateView(viewId) {
    // Hide all view panels
    const panels = document.querySelectorAll('.view-panel');
    panels.forEach(panel => {
      panel.classList.remove('active');
      panel.setAttribute('aria-hidden', 'true');
    });

    // Show active panel
    const active = $(`#view-${viewId}`);
    if (active) {
      active.classList.add('active');
      active.setAttribute('aria-hidden', 'false');
    }

    // Update dock active state
    const dockItems = document.querySelectorAll('.dock-item');
    dockItems.forEach(item => {
      item.classList.toggle('active', item.dataset.view === viewId);
      item.setAttribute('aria-selected', item.dataset.view === viewId ? 'true' : 'false');
    });

    // Update document title
    const label = viewId.charAt(0).toUpperCase() + viewId.slice(1);
    document.title = `AI-Do — ${label}`;
  }
}

const router = new Router();
export default router;
export { VIEWS };
