// Base Dashboard - Shared Dashboard Logic
import { navigate } from '../core/router.js';
import { toggleTheme, getTheme } from '../core/theme.js';
import { api } from '../core/api.js';
import { UIDashboard } from './UIDashboard.js';
import { UXDashboard } from './UXDashboard.js';
import { QADashboard } from './QADashboard.js';

const dashboards = {
  ui: UIDashboard,
  ux: UXDashboard,
  qa: QADashboard
};

export function renderDashboard(team, container) {
  const DashboardClass = dashboards[team];
  if (!DashboardClass) {
    console.error(`[Dashboard] Unknown team: ${team}`);
    return;
  }

  const dashboard = new DashboardClass(team);
  container.innerHTML = dashboard.render();

  // Setup event listeners after render
  setupDashboardEvents(dashboard, container);

  // Load metrics
  dashboard.loadMetrics();
}

export function hideDashboard(container) {
  container.classList.add('hidden');
  container.innerHTML = '';
}

function setupDashboardEvents(dashboard, container) {
  // Back button
  const backBtn = container.querySelector('.back-button');
  if (backBtn) {
    backBtn.addEventListener('click', () => {
      container.classList.remove('entering');
      container.classList.add('exiting');

      const handleTransitionEnd = () => {
        container.removeEventListener('transitionend', handleTransitionEnd);
        navigate('/');
      };

      container.addEventListener('transitionend', handleTransitionEnd);
      // Fallback in case transitionend doesn't fire
      setTimeout(() => {
        container.removeEventListener('transitionend', handleTransitionEnd);
        if (window.location.pathname !== '/') {
          navigate('/');
        }
      }, 500);
    });
  }

  // Theme toggle
  const themeBtn = container.querySelector('.theme-toggle');
  if (themeBtn) {
    themeBtn.addEventListener('click', () => {
      const newTheme = toggleTheme();
      updateThemeIcon(themeBtn, newTheme);
    });
    updateThemeIcon(themeBtn, getTheme());
  }

  // Action buttons
  container.querySelectorAll('.action-button').forEach(btn => {
    btn.addEventListener('click', () => {
      const action = btn.dataset.action;
      if (action && dashboard.handleAction) {
        dashboard.handleAction(action);
      }
    });
  });
}

function updateThemeIcon(button, theme) {
  const icon = button.querySelector('svg');
  if (theme === 'dark') {
    icon.innerHTML = `
      <path d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 1 1-8 0 4 4 0 0 1 8 0z"/>
    `;
  } else {
    icon.innerHTML = `
      <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
    `;
  }
}

// Base Dashboard Class
export class BaseDashboard {
  constructor(team) {
    this.team = team;
    this.metrics = {};
  }

  render() {
    return `
      <header class="dashboard-header">
        <div class="dashboard-header__left">
          <button class="back-button" aria-label="Back to home">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M19 12H5M12 19l-7-7 7-7"/>
            </svg>
            <span>back</span>
          </button>
          <div class="team-indicator">
            <div class="team-indicator__dots">
              <span class="team-indicator__dot ${this.team === 'ui' ? 'active' : ''}"></span>
              <span class="team-indicator__dot ${this.team === 'ux' ? 'active' : ''}"></span>
              <span class="team-indicator__dot ${this.team === 'qa' ? 'active' : ''}"></span>
            </div>
            <span class="team-indicator__name">${this.team.toUpperCase()} Team</span>
          </div>
        </div>
        <div class="dashboard-header__right">
          <button class="icon-button theme-toggle" aria-label="Toggle theme">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 1 1-8 0 4 4 0 0 1 8 0z"/>
            </svg>
          </button>
        </div>
      </header>
      ${this.renderMetricsBar()}
      ${this.renderActionZone()}
      ${this.renderActionDock()}
    `;
  }

  renderMetricsBar() {
    // Override in subclasses
    return '<div class="metrics-bar"></div>';
  }

  renderActionZone() {
    return `
      <main class="action-zone">
        <div class="action-zone__content">
          <h1 class="action-zone__title">Select an action</h1>
          <p class="action-zone__subtitle">Choose from the dock below to get started</p>
        </div>
      </main>
    `;
  }

  renderActionDock() {
    // Override in subclasses
    return '<nav class="action-dock"></nav>';
  }

  async loadMetrics() {
    try {
      this.metrics = await api.getTeamMetrics(this.team);
      this.updateMetricsDisplay();
    } catch (error) {
      console.error('[Dashboard] Failed to load metrics:', error);
    }
  }

  updateMetricsDisplay() {
    // Override in subclasses
  }

  handleAction(action) {
    console.log(`[Dashboard] Action: ${action}`);
    // Override in subclasses
  }
}

export default BaseDashboard;
