/**
 * dock.mjs — Bottom dock navigation
 * Renders navigation items and syncs active state with the store/router
 */

import store from '../store.mjs';
import router from '../router.mjs';
import { $, createElement, icon } from '../utils/dom.mjs';

const DOCK_ITEMS = [
  { id: 'chat',       icon: 'message-circle', label: 'Chat' },
  { id: 'activity',   icon: 'activity',       label: 'Activity' },
  { id: 'skills',     icon: 'zap',            label: 'Skills' },
  { id: 'knowledge',  icon: 'database',       label: 'Knowledge' },
  { id: 'workspaces', icon: 'folder',         label: 'Workspaces' },
  { id: 'settings',   icon: 'settings',       label: 'Settings' }
];

let dockEl = null;
let itemElements = {};

function init() {
  dockEl = $('nav.dock') || $('.dock');
  if (!dockEl) return;

  _buildDockItems();

  // Subscribe to currentView to update active state
  store.subscribe(
    (state) => state.ui.currentView,
    (view) => _setActive(view)
  );

  // Subscribe to activity feed for badge updates
  store.subscribe(
    (state) => state.activity.feed,
    () => _updateBadge()
  );

  // Set initial active state
  _setActive(store.getState().ui.currentView);
}

function _buildDockItems() {
  dockEl.innerHTML = '';
  itemElements = {};

  for (const item of DOCK_ITEMS) {
    const badge = createElement('span', {
      className: 'dock-badge hidden',
      'aria-hidden': 'true'
    });

    const btn = createElement('button', {
      className: 'dock-item',
      dataset: { view: item.id },
      'aria-label': item.label,
      'aria-selected': 'false'
    }, [
      createElement('span', { className: 'dock-icon' }, [icon(item.icon, { size: 24 })]),
      createElement('span', { className: 'dock-label' }, [item.label]),
      item.id === 'activity' ? badge : null
    ].filter(Boolean));

    btn.addEventListener('click', () => {
      router.navigate(item.id);
    });

    dockEl.appendChild(btn);
    itemElements[item.id] = { btn, badge: item.id === 'activity' ? badge : null };
  }
}

function _setActive(viewId) {
  for (const [id, { btn }] of Object.entries(itemElements)) {
    const isActive = id === viewId;
    btn.classList.toggle('active', isActive);
    btn.setAttribute('aria-selected', isActive ? 'true' : 'false');
  }
}

function _updateBadge() {
  const activityEntry = itemElements.activity;
  if (!activityEntry || !activityEntry.badge) return;

  const currentView = store.getState().ui.currentView;
  const feed = store.getState().activity.feed;

  // Show badge when there are activity events and user is not on activity view
  const hasUnread = currentView !== 'activity' && feed.length > 0;
  activityEntry.badge.classList.toggle('hidden', !hasUnread);
}

export { init };
