// DSS Team Portal - Main Entry Point
import { initRouter, navigate } from './js/core/router.js';
import { useStore } from './js/core/store.js';
import { initTheme } from './js/core/theme.js';
import { Being } from './js/conscious/Being.js';
import { renderDashboard, hideDashboard } from './js/dashboards/BaseDashboard.js';

// Initialize the application
class TeamPortal {
  constructor() {
    this.being = null;
    this.canvas = null;
  }

  async init() {
    console.log('[DSS] Initializing Team Portal...');

    // Initialize theme
    initTheme();

    // Initialize router
    initRouter(this.handleRoute.bind(this));

    // Initialize canvas and being
    this.canvas = document.getElementById('conscious-canvas');
    if (this.canvas) {
      this.being = new Being(this.canvas);
      this.being.start();
    }

    // Setup event listeners
    this.setupEventListeners();

    // Handle initial route
    this.handleRoute(window.location.pathname);

    console.log('[DSS] Team Portal initialized');
  }

  setupEventListeners() {
    // Team card clicks and keyboard navigation
    document.querySelectorAll('.team-card').forEach(card => {
      const handleActivation = () => {
        const team = card.dataset.team;
        this.navigateToTeam(team);
      };

      card.addEventListener('click', handleActivation);

      // Keyboard accessibility
      card.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          handleActivation();
        }
      });

      // Mouse interaction with being
      card.addEventListener('mouseenter', () => {
        if (this.being) {
          this.being.setTarget(card);
        }
      });

      card.addEventListener('mouseleave', () => {
        if (this.being) {
          this.being.clearTarget();
        }
      });
    });

    // Admin link - points to DSS API admin interface
    const ADMIN_URL = import.meta.env?.VITE_ADMIN_URL || '/api/admin';
    const adminLink = document.querySelector('.admin-link');
    if (adminLink) {
      adminLink.addEventListener('click', (e) => {
        e.preventDefault();
        // Open API docs/admin in new tab
        window.open(ADMIN_URL, '_blank');
      });
    }

    // Global mouse tracking for being
    document.addEventListener('mousemove', (e) => {
      if (this.being) {
        this.being.updateMousePosition(e.clientX, e.clientY);
      }
    });
  }

  navigateToTeam(team) {
    const landing = document.getElementById('landing');
    landing.classList.add('transitioning');

    const handleTransitionEnd = () => {
      landing.removeEventListener('transitionend', handleTransitionEnd);
      navigate(`/${team}`);
    };

    landing.addEventListener('transitionend', handleTransitionEnd);
    // Fallback for browsers/cases where transitionend doesn't fire
    setTimeout(() => {
      landing.removeEventListener('transitionend', handleTransitionEnd);
      if (window.location.pathname !== `/${team}`) {
        navigate(`/${team}`);
      }
    }, 400);
  }

  handleRoute(path) {
    const store = useStore.getState();
    const landing = document.getElementById('landing');
    const dashboard = document.getElementById('dashboard');

    if (path === '/' || path === '') {
      // Show landing
      landing.classList.remove('hidden', 'transitioning');
      dashboard.classList.add('hidden');
      dashboard.classList.remove('entering');
      store.setRoute('/');

      if (this.being) {
        this.being.setMode('idle');
      }
    } else {
      // Extract team from path (handles /ui, /ux, /qa)
      const segments = path.split('/').filter(Boolean);
      const team = segments[0];

      if (['ui', 'ux', 'qa'].includes(team)) {
        // Show dashboard
        landing.classList.add('hidden');
        dashboard.classList.remove('hidden');
        dashboard.classList.add('entering');
        dashboard.dataset.team = team;

        store.setRoute(path);
        store.setTeam(team);

        renderDashboard(team, dashboard);

        if (this.being) {
          this.being.setMode('background');
        }
      } else {
        // Redirect unknown routes to landing
        navigate('/');
      }
    }
  }
}

// Initialize on DOM ready
document.addEventListener('DOMContentLoaded', () => {
  const portal = new TeamPortal();
  portal.init();
});

export default TeamPortal;
