/**
 * router.js — Hash-based router. Maps #hash → view loader.
 * Views are registered with router.register(hash, loadFn).
 * Call router.navigate(hash) to switch views programmatically.
 */

import { S, bus } from './state.js';

const _routes = new Map();
let _current = null;

/**
 * Register a view route.
 * @param {string} hash   - Hash string without '#', e.g. 'board'
 * @param {Function} loadFn - Called when the route becomes active
 */
export function register(hash, loadFn) {
    _routes.set(hash, loadFn);
}

/** Navigate to a hash, updating location and triggering the loader. */
export function navigate(hash) {
    const target = hash.replace(/^#/, '');
    if (target === _current) return;
    _current = target;
    location.hash = target;
    _activate(target);
}

/** Called on initial load and hashchange. */
export function start() {
    window.addEventListener('hashchange', () => {
        const hash = location.hash.replace(/^#/, '') || 'board';
        _activate(hash);
    });
    // Activate current hash (or default)
    const initial = location.hash.replace(/^#/, '') || 'board';
    _activate(initial);
}

function _activate(hash) {
    // Panel show/hide
    document.querySelectorAll('.view-panel').forEach(p => {
        p.classList.toggle('active', p.dataset.view === hash);
    });
    // Nav highlight
    document.querySelectorAll('[data-nav]').forEach(el => {
        el.classList.toggle('active', el.dataset.nav === hash);
    });

    S.tab = hash;
    bus.emit('nav', hash);

    const fn = _routes.get(hash);
    if (fn) fn();
}
