/**
 * 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);
        window.location.hash = '#' + view;
      }
    );

    // Handle browser back/forward navigation
    window.addEventListener('hashchange', () => {
      const hash = window.location.hash.slice(1);
      const viewId = VIEWS.includes(hash) ? hash : 'chat';
      if (viewId !== store.getState().ui.currentView) {
        store.dispatch('SET_VIEW', viewId);
      }
    });

    // Apply initial view from hash, falling back to store default or 'chat'
    const initialHash = window.location.hash.slice(1);
    const initialView = VIEWS.includes(initialHash) ? initialHash : (store.getState().ui.currentView || 'chat');
    store.dispatch('SET_VIEW', initialView);
  }

  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 };
