// Atlas Dashboard JavaScript
class AtlasDashboard {
  constructor() {
    this.socket = null;
    this.data = {
      performance: {},
      security: {},
      errors: {},
      agile: {}
    };
    this.charts = {};
    this.init();
  }

  init() {
    this.setupWebSocket();
    this.setupNavigation();
    this.setupEventListeners();
    this.setupStoryCardListeners();
    this.loadInitialData();
  }

  setupWebSocket() {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const host = window.location.host;
    
    this.socket = io(`${protocol}//${host}`, {
      transports: ['websocket', 'polling']
    });

    this.socket.on('connect', () => {
      console.log('Connected to Atlas Dashboard');
      this.updateConnectionStatus('connected');
    });

    this.socket.on('disconnect', () => {
      console.log('Disconnected from Atlas Dashboard');
      this.updateConnectionStatus('disconnected');
    });

    this.socket.on('error', (error) => {
      console.error('WebSocket error:', error);
      this.updateConnectionStatus('error');
    });

    // Handle real-time data updates
    this.socket.on('performance_update', (data) => {
      this.handlePerformanceUpdate(data);
    });

    this.socket.on('security_update', (data) => {
      this.handleSecurityUpdate(data);
    });

    this.socket.on('errors_update', (data) => {
      this.handleErrorsUpdate(data);
    });

    this.socket.on('story_moved', (data) => {
      this.handleStoryMoved(data);
    });

    this.socket.on('story_updated', (data) => {
      this.handleStoryUpdated(data);
    });

    // Handle initial data
    this.socket.on('initial_performance', (data) => {
      this.data.performance = data;
      this.updateOverviewMetrics();
      this.updatePerformanceSection();
    });

    this.socket.on('initial_security', (data) => {
      this.data.security = data;
      this.updateSecuritySection();
    });

    this.socket.on('initial_errors', (data) => {
      this.data.errors = data;
      this.updateErrorsSection();
    });

    this.socket.on('initial_agile', (data) => {
      this.data.agile = data;
      this.updateAgileSection();
    });
  }

  updateConnectionStatus(status) {
    const statusElement = document.getElementById('connectionStatus');
    const icon = statusElement.querySelector('i');
    const text = statusElement.querySelector('span');

    statusElement.className = `connection-status ${status}`;
    
    switch (status) {
      case 'connected':
        icon.className = 'fas fa-circle';
        text.textContent = 'Connected';
        break;
      case 'disconnected':
        icon.className = 'fas fa-circle';
        text.textContent = 'Disconnected';
        break;
      case 'error':
        icon.className = 'fas fa-exclamation-circle';
        text.textContent = 'Connection Error';
        break;
      default:
        icon.className = 'fas fa-circle';
        text.textContent = 'Connecting...';
    }

    this.updateLastUpdated();
  }

  updateLastUpdated() {
    const element = document.getElementById('lastUpdated');
    element.textContent = `Last updated: ${new Date().toLocaleTimeString()}`;
  }

  setupNavigation() {
    const navButtons = document.querySelectorAll('.nav-btn');
    const sections = document.querySelectorAll('.dashboard-section');

    navButtons.forEach(btn => {
      btn.addEventListener('click', () => {
        const targetSection = btn.dataset.section;

        // Update nav buttons
        navButtons.forEach(b => b.classList.remove('active'));
        btn.classList.add('active');

        // Update sections
        sections.forEach(section => {
          section.classList.remove('active');
          if (section.id === targetSection) {
            section.classList.add('active');
          }
        });

        // Load section-specific data
        this.loadSectionData(targetSection);
      });
    });
  }

  setupEventListeners() {
    // Refresh button
    document.getElementById('refreshBtn').addEventListener('click', () => {
      this.refreshDashboard();
    });

    // Time range selectors
    document.getElementById('performanceTimeRange')?.addEventListener('change', (e) => {
      this.loadPerformanceData(e.target.value);
    });

    document.getElementById('errorTimeRange')?.addEventListener('change', (e) => {
      this.loadErrorData(e.target.value);
    });

    // Sprint selector
    document.getElementById('sprintSelector')?.addEventListener('change', (e) => {
      this.loadSprintData(e.target.value);
    });

    // Refresh board button
    document.getElementById('refreshBoard')?.addEventListener('click', () => {
      this.loadAgileData();
    });

    // Modal close button
    document.getElementById('closeModal')?.addEventListener('click', () => {
      this.closeStoryModal();
    });

    // Modal backdrop click
    document.querySelector('.modal-backdrop')?.addEventListener('click', () => {
      this.closeStoryModal();
    });

    // ESC key to close modal
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && this.isModalOpen()) {
        this.closeStoryModal();
      }
    });
  }

  setupStoryCardListeners() {
    // Use event delegation for dynamically created story cards
    document.addEventListener('click', (e) => {
      const storyCard = e.target.closest('.story-card');
      if (storyCard && !e.target.closest('.story-tag')) {
        e.preventDefault();
        const storyId = storyCard.dataset.storyId;
        this.openStoryModal(storyId);
      }
    });
  }

  async loadInitialData() {
    try {
      // Load health status
      const healthResponse = await fetch('/api/health');
      const healthData = await healthResponse.json();
      this.updateSystemHealth(healthData);

      // Load overview data
      await this.loadOverviewData();
      
    } catch (error) {
      console.error('Error loading initial data:', error);
      this.showError('Failed to load initial dashboard data');
    }
  }

  async loadOverviewData() {
    try {
      // Load performance overview
      const perfResponse = await fetch('/api/metrics/overview');
      if (perfResponse.ok) {
        const perfData = await perfResponse.json();
        this.data.performance = perfData.data;
      }

      // Load security overview
      const secResponse = await fetch('/api/security/status');
      if (secResponse.ok) {
        const secData = await secResponse.json();
        this.data.security = secData.data;
      }

      // Load error statistics
      const errorResponse = await fetch('/api/errors/stats');
      if (errorResponse.ok) {
        const errorData = await errorResponse.json();
        this.data.errors = errorData.data;
      }

      // Load agile overview
      const agileResponse = await fetch('/api/agile/sprints');
      if (agileResponse.ok) {
        const agileData = await agileResponse.json();
        this.data.agile = agileData.data;
      }

      this.updateOverviewMetrics();
      this.loadActivityFeed();

    } catch (error) {
      console.error('Error loading overview data:', error);
    }
  }

  updateOverviewMetrics() {
    const performance = this.data.performance;
    const security = this.data.security;
    const errors = this.data.errors;
    const agile = this.data.agile;

    // Performance metric
    if (performance.successRate !== undefined) {
      document.getElementById('overviewPerformance').textContent = 
        `${(performance.successRate * 100).toFixed(1)}%`;
      this.updateTrend('performanceTrend', performance.trend || 'stable');
    }

    // Security metric
    if (security.overall?.securityScore !== undefined) {
      document.getElementById('overviewSecurity').textContent = 
        security.overall.securityScore.toFixed(1);
      this.updateTrend('securityTrend', security.overall.trend || 'stable');
    }

    // Errors metric
    if (errors.totalErrors !== undefined) {
      document.getElementById('overviewErrors').textContent = errors.totalErrors;
      this.updateTrend('errorsTrend', errors.trends?.trend || 'stable');
    }

    // Sprint metric
    if (agile.sprints && agile.sprints.length > 0) {
      const activeSprint = agile.sprints.find(s => s.status === 'active');
      if (activeSprint) {
        const progress = `${activeSprint.storiesCompleted}/${activeSprint.storiesTotal}`;
        document.getElementById('overviewSprint').textContent = progress;
        
        const completionRate = activeSprint.storiesTotal > 0 ? (activeSprint.storiesCompleted / activeSprint.storiesTotal) * 100 : 0;
        const trend = completionRate >= 75 ? 'positive' : completionRate >= 50 ? 'stable' : 'negative';
        this.updateTrend('sprintTrend', trend);
      }
    }
  }

  updateTrend(elementId, trend) {
    const element = document.getElementById(elementId);
    element.className = `metric-trend ${trend}`;
    
    const icons = {
      positive: 'fas fa-arrow-up',
      negative: 'fas fa-arrow-down',
      stable: 'fas fa-minus',
      increasing: 'fas fa-arrow-up',
      decreasing: 'fas fa-arrow-down'
    };

    const texts = {
      positive: 'Improving',
      negative: 'Declining',
      stable: 'Stable',
      increasing: 'Increasing',
      decreasing: 'Decreasing'
    };

    element.innerHTML = `
      <i class="${icons[trend] || 'fas fa-minus'}"></i>
      ${texts[trend] || 'Stable'}
    `;
  }

  updateSystemHealth(healthData) {
    const element = document.getElementById('systemHealth');
    const icon = element.querySelector('i');
    const text = element.querySelector('span');

    if (healthData.success) {
      element.className = 'system-health healthy';
      icon.className = 'fas fa-heart';
      text.textContent = 'System Healthy';
    } else {
      element.className = 'system-health error';
      icon.className = 'fas fa-exclamation-triangle';
      text.textContent = 'System Issues';
    }
  }

  async loadActivityFeed() {
    const feedElement = document.getElementById('activityFeed');
    
    try {
      // Combine recent activities from different sources
      const activities = [];

      // Add performance activities
      if (this.data.performance.recentExecutions) {
        this.data.performance.recentExecutions.slice(0, 3).forEach(exec => {
          activities.push({
            type: 'performance',
            icon: 'fas fa-tachometer-alt',
            text: `Tool "${exec.toolName}" executed successfully`,
            time: exec.timestamp,
            severity: exec.success ? 'success' : 'error'
          });
        });
      }

      // Add security activities
      if (this.data.security.recentEvents) {
        this.data.security.recentEvents.slice(0, 2).forEach(event => {
          activities.push({
            type: 'security',
            icon: 'fas fa-shield-alt',
            text: event.description,
            time: event.timestamp,
            severity: event.severity
          });
        });
      }

      // Add error activities
      if (this.data.errors.recentErrors) {
        this.data.errors.recentErrors.slice(0, 2).forEach(error => {
          activities.push({
            type: 'error',
            icon: 'fas fa-bug',
            text: `Error in ${error.tool}: ${error.message}`,
            time: error.timestamp,
            severity: error.severity
          });
        });
      }

      // Sort by time and limit to recent items
      activities.sort((a, b) => new Date(b.time) - new Date(a.time));
      const recentActivities = activities.slice(0, 8);

      // Render activities
      if (recentActivities.length === 0) {
        feedElement.innerHTML = `
          <div class="activity-item">
            <i class="fas fa-info-circle"></i>
            <span>No recent activity</span>
          </div>
        `;
      } else {
        feedElement.innerHTML = recentActivities.map(activity => `
          <div class="activity-item">
            <i class="${activity.icon} ${activity.severity}"></i>
            <div class="activity-content">
              <div class="activity-text">${activity.text}</div>
              <div class="activity-time">${this.formatTime(activity.time)}</div>
            </div>
          </div>
        `).join('');
      }

    } catch (error) {
      console.error('Error loading activity feed:', error);
      feedElement.innerHTML = `
        <div class="activity-item">
          <i class="fas fa-exclamation-triangle"></i>
          <span>Failed to load recent activity</span>
        </div>
      `;
    }
  }

  loadSectionData(section) {
    switch (section) {
      case 'performance':
        this.loadPerformanceData();
        break;
      case 'agile':
        this.loadAgileData();
        break;
      case 'epics':
        this.loadEpicsData();
        break;
      case 'security':
        this.loadSecurityData();
        break;
      case 'errors':
        this.loadErrorData();
        break;
    }
  }

  async loadPerformanceData(timeRange = '24h') {
    try {
      const response = await fetch(`/api/metrics/overview?timeRange=${timeRange}`);
      if (!response.ok) throw new Error('Failed to load performance data');
      
      const data = await response.json();
      this.data.performance = data.data;
      this.updatePerformanceSection();
      
    } catch (error) {
      console.error('Error loading performance data:', error);
      this.showError('Failed to load performance data');
    }
  }

  updatePerformanceSection() {
    // Update performance charts
    if (window.updatePerformanceCharts) {
      window.updatePerformanceCharts(this.data.performance);
    }

    // Update performance alerts
    this.loadPerformanceAlerts();
  }

  async loadPerformanceAlerts() {
    try {
      const response = await fetch('/api/metrics/alerts');
      if (!response.ok) return;
      
      const data = await response.json();
      const alertsContainer = document.getElementById('performanceAlerts');
      
      if (data.data.alerts.length === 0) {
        alertsContainer.innerHTML = `
          <div class="alert-item">
            <i class="fas fa-check-circle"></i>
            <span>No performance alerts</span>
          </div>
        `;
      } else {
        alertsContainer.innerHTML = data.data.alerts.map(alert => `
          <div class="alert-item ${alert.severity}">
            <i class="fas fa-exclamation-triangle"></i>
            <div class="alert-content">
              <div class="alert-title">${alert.title}</div>
              <div class="alert-message">${alert.message}</div>
              ${alert.suggestion ? `<div class="alert-suggestion">${alert.suggestion}</div>` : ''}
            </div>
          </div>
        `).join('');
      }
    } catch (error) {
      console.error('Error loading performance alerts:', error);
    }
  }

  async loadAgileData() {
    try {
      // Load sprints for selector
      let hasActiveSprint = false;
      const sprintsResponse = await fetch('/api/agile/sprints');
      if (sprintsResponse.ok) {
        const sprintsData = await sprintsResponse.json();
        const sprints = sprintsData.data.sprints || [];
        
        if (sprints.length > 0) {
          this.updateSprintSelector(sprints);
          
          // Load active sprint by default
          const activeSprint = sprints.find(s => s.status === 'active');
          if (activeSprint) {
            await this.loadSprintData(activeSprint.id);
            hasActiveSprint = true;
          }
        } else {
          // No sprints available - show message and load all stories
          this.updateSprintSelector([]);
          document.getElementById('sprintInfo').innerHTML = `
            <div class="no-sprint-message">
              <h3>No Sprints Available</h3>
              <p>Showing all stories in backlog mode</p>
            </div>
          `;
        }
      }

      // Always load all stories if no active sprint was found
      if (!hasActiveSprint) {
        await this.loadAllStories();
      }

    } catch (error) {
      console.error('Error loading agile data:', error);
      this.showError('Failed to load agile data');
    }
  }

  updateSprintSelector(sprints) {
    const selector = document.getElementById('sprintSelector');
    if (sprints.length === 0) {
      selector.innerHTML = '<option value="">No sprints available - Showing all stories</option>';
      selector.disabled = true;
    } else {
      selector.disabled = false;
      selector.innerHTML = sprints.map(sprint => `
        <option value="${sprint.id}" ${sprint.status === 'active' ? 'selected' : ''}>
          ${sprint.name} (${sprint.status})
        </option>
      `).join('');
    }
  }

  async loadSprintData(sprintId) {
    if (!sprintId) return;

    try {
      // Load sprint details
      const sprintResponse = await fetch(`/api/agile/sprint/${sprintId}`);
      if (sprintResponse.ok) {
        const sprintData = await sprintResponse.json();
        this.updateSprintInfo(sprintData.data);
      }

      // Load stories for the sprint
      const storiesResponse = await fetch(`/api/agile/stories?sprintId=${sprintId}`);
      if (storiesResponse.ok) {
        const storiesData = await storiesResponse.json();
        this.updateKanbanBoard(storiesData.data.stories);
      }

      // Load burndown chart
      this.loadBurndownChart(sprintId);
      
      // Load velocity chart
      this.loadVelocityChart();

    } catch (error) {
      console.error('Error loading sprint data:', error);
    }
  }

  updateSprintInfo(sprint) {
    const sprintInfoElement = document.getElementById('sprintInfo');
    const progress = sprint.storyPointsPlanned > 0 ? (sprint.storyPointsCompleted / sprint.storyPointsPlanned * 100) : 0;
    const daysLeft = this.calculateDaysLeft(sprint.endDate);
    const progressColor = progress >= 80 ? 'var(--md-success)' : progress >= 50 ? 'var(--md-warning)' : 'var(--md-error)';
    
    sprintInfoElement.innerHTML = `
      <div class="sprint-details">
        <div class="sprint-header">
          <h3><i class="fas fa-rocket"></i> ${sprint.name}</h3>
          <span class="sprint-status ${sprint.status}">${sprint.status}</span>
        </div>
        <div class="sprint-meta">
          <span><i class="fas fa-bullseye"></i> <strong>Goal:</strong> ${sprint.goal}</span>
          <span><i class="fas fa-calendar-alt"></i> <strong>Duration:</strong> ${this.formatDateRange(sprint.startDate, sprint.endDate)}</span>
          <span><i class="fas fa-clock"></i> <strong>Days Left:</strong> ${daysLeft > 0 ? daysLeft : 0} days</span>
          <span><i class="fas fa-users"></i> <strong>Team Size:</strong> ${sprint.team ? sprint.team.length : 0} members</span>
        </div>
        <div class="sprint-progress">
          <div class="sprint-progress-header">
            <span><strong>${progress.toFixed(1)}%</strong> Complete</span>
            <span>${sprint.storyPointsCompleted || 0} / ${sprint.storyPointsPlanned || 0} points</span>
          </div>
          <div class="progress-bar">
            <div class="progress-fill" style="width: ${progress}%; background: ${progressColor}"></div>
          </div>
        </div>
        <div class="sprint-metrics">
          <div class="metric-card mini">
            <i class="fas fa-check-circle"></i>
            <div class="metric-content">
              <div class="metric-value">${sprint.storiesCompleted}</div>
              <div class="metric-label">Completed</div>
            </div>
          </div>
          <div class="metric-card mini">
            <i class="fas fa-tasks"></i>
            <div class="metric-content">
              <div class="metric-value">${sprint.storiesTotal - sprint.storiesCompleted}</div>
              <div class="metric-label">Remaining</div>
            </div>
          </div>
          <div class="metric-card mini">
            <i class="fas fa-tachometer-alt"></i>
            <div class="metric-content">
              <div class="metric-value">${sprint.velocity || 0}</div>
              <div class="metric-label">Velocity</div>
            </div>
          </div>
          <div class="metric-card mini">
            <i class="fas fa-fire"></i>
            <div class="metric-content">
              <div class="metric-value">${Math.round((sprint.storyPointsCompleted || 0) / (sprint.duration || 14) * 7)}</div>
              <div class="metric-label">Weekly Rate</div>
            </div>
          </div>
        </div>
      </div>
    `;
  }

  calculateDaysLeft(endDate) {
    const end = new Date(endDate);
    const now = new Date();
    const diffTime = end - now;
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  }

  updateKanbanBoard(stories) {
    // Group stories by status
    const storyGroups = {
      'todo': [],
      'in-progress': [],
      'review': [],
      'done': []
    };

    stories.forEach(story => {
      let status = story.status || 'todo';
      // Map backend status to frontend status
      if (status === 'in_progress') status = 'in-progress';
      if (status === 'backlog') status = 'todo';
      
      if (storyGroups[status]) {
        storyGroups[status].push(story);
      }
    });

    // Update each column
    Object.keys(storyGroups).forEach(status => {
      const container = document.getElementById(`${status === 'in-progress' ? 'inProgress' : status}Cards`);
      const countElement = container.parentElement.querySelector('.story-count');
      
      countElement.textContent = storyGroups[status].length;
      
      if (storyGroups[status].length === 0) {
        container.innerHTML = `
          <div class="empty-state">
            <div class="empty-state-icon">
              <i class="fas fa-inbox"></i>
            </div>
            <div class="empty-state-title">No stories</div>
            <div class="empty-state-message">Drag stories here to update their status</div>
          </div>
        `;
      } else {
        container.innerHTML = storyGroups[status].map(story => 
          this.createStoryCard(story)
        ).join('');
      }
    });

    // Setup drag and drop if available
    if (window.setupDragAndDrop) {
      window.setupDragAndDrop();
    }
  }

  async loadAllStories() {
    try {
      // Load all stories without sprint filter
      const storiesResponse = await fetch('/api/agile/stories?limit=100');
      if (storiesResponse.ok) {
        const storiesData = await storiesResponse.json();
        const stories = storiesData.data.stories || [];
        
        console.log('Loaded', stories.length, 'stories for backlog view');
        this.updateKanbanBoard(stories);
        
        // Update backlog summary
        this.updateBacklogSummary(stories);
      } else {
        console.error('Failed to load stories:', storiesResponse.status);
        this.showError('Failed to load stories');
      }
    } catch (error) {
      console.error('Error loading all stories:', error);
      this.showError('Failed to load stories');
    }
  }

  updateBacklogSummary(stories) {
    // Count stories by priority and status
    const summary = {
      total: stories.length,
      byPriority: { low: 0, medium: 0, high: 0, critical: 0 },
      byStatus: { todo: 0, 'in-progress': 0, review: 0, done: 0, backlog: 0 }
    };

    stories.forEach(story => {
      summary.byPriority[story.priority] = (summary.byPriority[story.priority] || 0) + 1;
      summary.byStatus[story.status] = (summary.byStatus[story.status] || 0) + 1;
    });

    // Update sprint info section with backlog summary
    document.getElementById('sprintInfo').innerHTML += `
      <div class="backlog-summary">
        <h4>Backlog Summary</h4>
        <div class="summary-stats">
          <span><strong>Total Stories:</strong> ${summary.total}</span>
          <span><strong>High Priority:</strong> ${summary.byPriority.high || 0}</span>
          <span><strong>In Progress:</strong> ${summary.byStatus['in-progress'] || 0}</span>
          <span><strong>Completed:</strong> ${summary.byStatus.done || 0}</span>
        </div>
      </div>
    `;
  }

  createStoryCard(story) {
    const initials = story.assignee ? 
      story.assignee.split(' ').map(n => n[0]).join('').toUpperCase() : 'UN';
    
    // Generate color based on assignee name for consistent avatar colors
    const colorIndex = story.assignee ? 
      (story.assignee.charCodeAt(0) + story.assignee.charCodeAt(1)) % 10 + 1 : 1;

    return `
      <div class="story-card" 
           data-story-id="${story.id}" 
           data-priority="${story.priority || 'medium'}"
           draggable="true">
        <div class="story-header">
          <span class="story-id">${story.id}</span>
          <span class="story-points">${story.storyPoints || 0}</span>
        </div>
        <div class="story-title" title="${story.title}">${story.title}</div>
        <div class="story-assignee">
          <div class="avatar" data-color="${colorIndex}">${initials}</div>
          <span>${story.assignee || 'Unassigned'}</span>
        </div>
        ${story.tags && story.tags.length > 0 ? `
          <div class="story-tags">
            ${story.tags.map(tag => `<span class="story-tag">${tag}</span>`).join('')}
          </div>
        ` : ''}
        ${story.epic ? `
          <div class="story-epic">
            <i class="fas fa-layer-group"></i>
            <span class="epic-id">${story.epic}</span>
          </div>
        ` : ''}
        <div class="story-progress">
          <div class="progress-bar">
            <div class="progress-fill" style="width: ${story.progress || 0}%"></div>
          </div>
        </div>
      </div>
    `;
  }

  async loadBurndownChart(sprintId) {
    try {
      const response = await fetch(`/api/agile/burndown/${sprintId}`);
      if (!response.ok) return;
      
      const data = await response.json();
      
      if (window.updateBurndownChart) {
        window.updateBurndownChart(data.data);
      }
    } catch (error) {
      console.error('Error loading burndown chart:', error);
    }
  }

  async loadVelocityChart() {
    try {
      const response = await fetch('/api/agile/velocity');
      if (!response.ok) return;
      
      const data = await response.json();
      
      if (window.updateVelocityChart) {
        window.updateVelocityChart(data.data);
      }
    } catch (error) {
      console.error('Error loading velocity chart:', error);
    }
  }

  updateAgileSection() {
    // This will be called when real-time agile updates are received
    this.loadAgileData();
  }

  async loadSecurityData() {
    try {
      // Load security status
      const statusResponse = await fetch('/api/security/status');
      if (statusResponse.ok) {
        const statusData = await statusResponse.json();
        this.updateSecurityMetrics(statusData.data);
      }

      // Load security alerts
      const alertsResponse = await fetch('/api/security/alerts');
      if (alertsResponse.ok) {
        const alertsData = await alertsResponse.json();
        this.updateSecurityAlerts(alertsData.data.alerts);
      }

      // Load approval requests
      const approvalsResponse = await fetch('/api/security/approvals');
      if (approvalsResponse.ok) {
        const approvalsData = await approvalsResponse.json();
        this.updateApprovalsList(approvalsData.data.approvals);
      }

    } catch (error) {
      console.error('Error loading security data:', error);
    }
  }

  updateSecurityMetrics(securityData) {
    const { overall, recentEvents, policies } = securityData;

    document.getElementById('securityScore').textContent = 
      overall?.securityScore?.toFixed(1) || '--';
    document.getElementById('recentEvents').textContent = 
      recentEvents?.total || '--';
    document.getElementById('pendingApprovals').textContent = 
      overall?.pendingApprovals || '--';

    // Update security status
    const statusElement = document.getElementById('securityStatus');
    const icon = statusElement.querySelector('i');
    const text = statusElement.querySelector('span');

    if (overall?.status === 'healthy') {
      statusElement.className = 'security-status healthy';
      icon.className = 'fas fa-shield-alt';
      text.textContent = 'Security Status: Healthy';
    } else {
      statusElement.className = 'security-status warning';
      icon.className = 'fas fa-exclamation-triangle';
      text.textContent = 'Security Status: Needs Attention';
    }
  }

  updateSecurityAlerts(alerts) {
    const alertsContainer = document.getElementById('securityAlerts');
    
    if (alerts.length === 0) {
      alertsContainer.innerHTML = `
        <div class="alert-item">
          <i class="fas fa-check-circle"></i>
          <span>No security alerts</span>
        </div>
      `;
    } else {
      alertsContainer.innerHTML = alerts.map(alert => `
        <div class="alert-item ${alert.severity}">
          <i class="fas fa-exclamation-triangle"></i>
          <div class="alert-content">
            <div class="alert-title">${alert.title}</div>
            <div class="alert-message">${alert.message}</div>
            <div class="alert-time">${this.formatTime(alert.timestamp)}</div>
          </div>
        </div>
      `).join('');
    }
  }

  updateApprovalsList(approvals) {
    const approvalsContainer = document.getElementById('approvalsList');
    
    if (approvals.length === 0) {
      approvalsContainer.innerHTML = `
        <div class="approval-item">
          <i class="fas fa-check-circle"></i>
          <span>No pending approvals</span>
        </div>
      `;
    } else {
      approvalsContainer.innerHTML = approvals.map(approval => `
        <div class="approval-item">
          <div class="approval-header">
            <span class="approval-title">${approval.operation}</span>
            <span class="approval-risk ${approval.riskLevel}">${approval.riskLevel} risk</span>
          </div>
          <div class="approval-details">
            ${approval.reason}
            <br>
            <small>Requested: ${this.formatTime(approval.timestamp)}</small>
          </div>
          <div class="approval-actions">
            <button class="btn btn-approve" onclick="dashboard.processApproval('${approval.id}', 'approve')">
              Approve
            </button>
            <button class="btn btn-deny" onclick="dashboard.processApproval('${approval.id}', 'deny')">
              Deny
            </button>
          </div>
        </div>
      `).join('');
    }
  }

  async processApproval(approvalId, decision) {
    try {
      const reason = prompt(`Please provide a reason for ${decision}ing this request:`);
      if (!reason) return;

      const response = await fetch(`/api/security/approval/${approvalId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ decision, reason })
      });

      if (response.ok) {
        this.showSuccess(`Approval request ${decision}d successfully`);
        this.loadSecurityData(); // Refresh the data
      } else {
        this.showError(`Failed to ${decision} approval request`);
      }
    } catch (error) {
      console.error(`Error ${decision}ing approval:`, error);
      this.showError(`Failed to ${decision} approval request`);
    }
  }

  updateSecuritySection() {
    this.loadSecurityData();
  }

  async loadErrorData(timeRange = '24h') {
    try {
      // Load error statistics
      const statsResponse = await fetch(`/api/errors/stats?timeRange=${timeRange}`);
      if (statsResponse.ok) {
        const statsData = await statsResponse.json();
        this.updateErrorStats(statsData.data);
      }

      // Load error timeline
      const timelineResponse = await fetch(`/api/errors/timeline?timeRange=${timeRange}`);
      if (timelineResponse.ok) {
        const timelineData = await timelineResponse.json();
        this.updateErrorTimeline(timelineData.data.timeline);
      }

      // Load error trends for charts
      const trendsResponse = await fetch(`/api/errors/trends?timeRange=${timeRange}`);
      if (trendsResponse.ok) {
        const trendsData = await trendsResponse.json();
        if (window.updateErrorCharts) {
          window.updateErrorCharts(trendsData.data);
        }
      }

    } catch (error) {
      console.error('Error loading error data:', error);
    }
  }

  updateErrorStats(stats) {
    document.getElementById('totalErrors').textContent = stats.totalErrors || 0;
    document.getElementById('errorRate').textContent = `${stats.errorRate || 0}/hr`;
    document.getElementById('criticalErrors').textContent = stats.criticalErrors || 0;
    document.getElementById('errorPatterns').textContent = stats.patternsFound || 0;
  }

  updateErrorTimeline(timeline) {
    const timelineContainer = document.getElementById('errorTimeline');
    
    if (timeline.length === 0) {
      timelineContainer.innerHTML = `
        <div class="timeline-item">
          <i class="fas fa-check-circle"></i>
          <span>No errors in the selected time range</span>
        </div>
      `;
    } else {
      timelineContainer.innerHTML = timeline.map(error => `
        <div class="timeline-item">
          <div class="error-severity ${error.severity}"></div>
          <div class="error-details">
            <div class="error-title">${error.message}</div>
            <div class="error-meta">
              ${error.tool || 'Unknown tool'} • ${error.severity} • ${this.formatTime(error.timestamp)}
            </div>
          </div>
        </div>
      `).join('');
    }
  }

  updateErrorsSection() {
    this.loadErrorData();
  }

  // Real-time update handlers
  handlePerformanceUpdate(data) {
    this.data.performance = { ...this.data.performance, ...data.metrics };
    this.updateOverviewMetrics();
    if (document.querySelector('#performance.active')) {
      this.updatePerformanceSection();
    }
    this.updateLastUpdated();
  }

  handleSecurityUpdate(data) {
    this.data.security = { ...this.data.security, ...data.status };
    this.updateOverviewMetrics();
    if (document.querySelector('#security.active')) {
      this.updateSecuritySection();
    }
    this.updateLastUpdated();
  }

  handleErrorsUpdate(data) {
    this.data.errors = { ...this.data.errors, ...data.patterns };
    this.updateOverviewMetrics();
    if (document.querySelector('#errors.active')) {
      this.updateErrorsSection();
    }
    this.updateLastUpdated();
  }

  handleStoryMoved(data) {
    // Update the kanban board in real-time
    if (document.querySelector('#agile.active')) {
      this.moveStoryCard(data.storyId, data.fromColumn, data.toColumn);
    }
    this.updateLastUpdated();
  }

  handleStoryUpdated(data) {
    // Update story card in real-time
    if (document.querySelector('#agile.active')) {
      this.updateStoryCard(data.storyId, data.updates);
    }
    this.updateLastUpdated();
  }

  moveStoryCard(storyId, fromColumn, toColumn) {
    const storyCard = document.querySelector(`[data-story-id="${storyId}"]`);
    if (!storyCard) return;

    const fromContainer = document.getElementById(`${fromColumn === 'in-progress' ? 'inProgress' : fromColumn}Cards`);
    const toContainer = document.getElementById(`${toColumn === 'in-progress' ? 'inProgress' : toColumn}Cards`);
    
    if (fromContainer && toContainer) {
      toContainer.appendChild(storyCard);
      
      // Update story counts
      this.updateColumnCounts();
    }
  }

  updateStoryCard(storyId, updates) {
    const storyCard = document.querySelector(`[data-story-id="${storyId}"]`);
    if (!storyCard) return;

    // Update story card content based on updates
    // This would need to be implemented based on the specific updates
    console.log('Story updated:', storyId, updates);
  }

  updateColumnCounts() {
    ['todo', 'inProgress', 'review', 'done'].forEach(column => {
      const container = document.getElementById(`${column}Cards`);
      const countElement = container.parentElement.querySelector('.story-count');
      const storyCards = container.querySelectorAll('.story-card');
      countElement.textContent = storyCards.length;
    });
  }

  // Utility methods
  refreshDashboard() {
    const refreshBtn = document.getElementById('refreshBtn');
    const icon = refreshBtn.querySelector('i');
    
    icon.classList.add('fa-spin');
    
    this.loadInitialData().finally(() => {
      setTimeout(() => {
        icon.classList.remove('fa-spin');
      }, 500);
    });
  }

  formatTime(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    
    if (diff < 60000) return 'Just now';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
    return date.toLocaleDateString();
  }

  formatDateRange(startDate, endDate) {
    const start = new Date(startDate).toLocaleDateString();
    const end = new Date(endDate).toLocaleDateString();
    return `${start} - ${end}`;
  }

  showError(message) {
    console.error(message);
    // Could implement a toast notification system here
  }

  showSuccess(message) {
    console.log(message);
    // Could implement a toast notification system here
  }

  // Story Modal Methods
  async openStoryModal(storyId) {
    const modal = document.getElementById('storyDetailModal');
    const contentEl = document.getElementById('storyDetailContent');
    
    // Show loading state
    contentEl.innerHTML = `
      <div class="loading-state">
        <i class="fas fa-spinner fa-spin"></i>
        Loading story details...
      </div>
    `;
    
    // Reset modal state and show with animation
    modal.style.display = '';
    modal.classList.remove('show');
    
    // Force reflow to ensure the modal is positioned before animation
    void modal.offsetHeight;
    
    // Show modal with animation
    requestAnimationFrame(() => {
      modal.classList.add('show');
    });
    
    try {
      // Fetch story details
      const response = await fetch(`/api/agile/stories/${storyId}`);
      if (response.ok) {
        const data = await response.json();
        const story = data.data;
        this.renderStoryDetails(story);
      } else {
        // If individual story endpoint doesn't exist, find from loaded stories
        const story = this.findStoryById(storyId);
        if (story) {
          this.renderStoryDetails(story);
        } else {
          contentEl.innerHTML = `
            <div class="error-state">
              <i class="fas fa-exclamation-triangle"></i>
              Failed to load story details
            </div>
          `;
        }
      }
    } catch (error) {
      console.error('Error loading story details:', error);
      // Try to find story from already loaded data
      const story = this.findStoryById(storyId);
      if (story) {
        this.renderStoryDetails(story);
      } else {
        contentEl.innerHTML = `
          <div class="error-state">
            <i class="fas fa-exclamation-triangle"></i>
            Failed to load story details
          </div>
        `;
      }
    }
  }

  findStoryById(storyId) {
    // Search through all loaded stories
    const allContainers = document.querySelectorAll('.cards-container');
    for (const container of allContainers) {
      const card = container.querySelector(`[data-story-id="${storyId}"]`);
      if (card) {
        // Extract story data from card (simplified version)
        return {
          id: storyId,
          title: card.querySelector('.story-title')?.textContent || '',
          description: 'Story description would be loaded from the full API',
          status: container.parentElement.dataset.status || 'todo',
          priority: card.dataset.priority || 'medium',
          storyPoints: card.querySelector('.story-points')?.textContent || 0,
          assignee: card.querySelector('.story-assignee span')?.textContent || 'Unassigned',
          tags: Array.from(card.querySelectorAll('.story-tag')).map(tag => tag.textContent),
          epic: card.querySelector('.epic-id')?.textContent || null,
          progress: parseInt(card.querySelector('.progress-fill')?.style.width || '0')
        };
      }
    }
    return null;
  }

  renderStoryDetails(story) {
    const contentEl = document.getElementById('storyDetailContent');
    
    contentEl.innerHTML = `
      <div class="story-detail-header">
        <div>
          <h3 class="story-detail-title">${story.title}</h3>
          <div class="story-detail-meta">
            <span class="story-id">${story.id}</span>
            <span class="story-detail-priority" data-priority="${story.priority}">
              <i class="fas fa-flag"></i>
              ${story.priority}
            </span>
            <span class="story-points-badge">
              <i class="fas fa-bolt"></i>
              ${story.storyPoints} points
            </span>
          </div>
        </div>
        <div class="story-detail-actions">
          <button class="btn-icon" title="Edit">
            <i class="fas fa-edit"></i>
          </button>
          <button class="btn-icon" title="Delete">
            <i class="fas fa-trash"></i>
          </button>
        </div>
      </div>

      <div class="story-detail-section">
        <h4>Description</h4>
        <p class="story-description">${story.description || 'No description provided.'}</p>
      </div>

      <div class="story-detail-section">
        <h4>Details</h4>
        <div class="story-detail-grid">
          <div class="detail-item">
            <label>Status</label>
            <select class="story-status-select" data-story-id="${story.id}">
              <option value="backlog" ${story.status === 'backlog' ? 'selected' : ''}>Backlog</option>
              <option value="todo" ${story.status === 'todo' ? 'selected' : ''}>To Do</option>
              <option value="in_progress" ${story.status === 'in_progress' ? 'selected' : ''}>In Progress</option>
              <option value="review" ${story.status === 'review' ? 'selected' : ''}>Review</option>
              <option value="testing" ${story.status === 'testing' ? 'selected' : ''}>Testing</option>
              <option value="done" ${story.status === 'done' ? 'selected' : ''}>Done</option>
              <option value="blocked" ${story.status === 'blocked' ? 'selected' : ''}>Blocked</option>
            </select>
          </div>
          <div class="detail-item">
            <label>Assignee</label>
            <div class="assignee-selector">
              <div class="avatar">${this.getInitials(story.assignee)}</div>
              <span>${story.assignee || 'Unassigned'}</span>
            </div>
          </div>
          <div class="detail-item">
            <label>Epic</label>
            <span class="epic-link">${story.epic || 'No epic assigned'}</span>
          </div>
          <div class="detail-item">
            <label>Sprint</label>
            <span>${story.sprintId || 'No sprint assigned'}</span>
          </div>
        </div>
      </div>

      ${story.acceptanceCriteria && story.acceptanceCriteria.length > 0 ? `
        <div class="story-detail-section">
          <h4>Acceptance Criteria</h4>
          <ul class="acceptance-criteria-list">
            ${story.acceptanceCriteria.map(criteria => `
              <li class="acceptance-item">
                <input type="checkbox" ${criteria.completed ? 'checked' : ''}>
                <span>${criteria.text || criteria}</span>
              </li>
            `).join('')}
          </ul>
        </div>
      ` : ''}

      ${story.tags && story.tags.length > 0 ? `
        <div class="story-detail-section">
          <h4>Tags</h4>
          <div class="story-tags">
            ${story.tags.map(tag => `<span class="story-tag">${tag}</span>`).join('')}
          </div>
        </div>
      ` : ''}

      <div class="story-detail-section">
        <h4>Progress</h4>
        <div class="progress-section">
          <div class="progress-bar large">
            <div class="progress-fill" style="width: ${story.progress || 0}%"></div>
          </div>
          <span class="progress-text">${story.progress || 0}% Complete</span>
        </div>
      </div>

      ${story.timeTracking ? `
        <div class="story-detail-section">
          <h4>Time Tracking</h4>
          <div class="time-tracking-grid">
            <div class="time-item">
              <label>Estimated</label>
              <span>${story.timeTracking.estimated || 0}h</span>
            </div>
            <div class="time-item">
              <label>Actual</label>
              <span>${story.timeTracking.actual || 0}h</span>
            </div>
            <div class="time-item">
              <label>Remaining</label>
              <span>${story.timeTracking.remaining || 0}h</span>
            </div>
          </div>
        </div>
      ` : ''}

      <div class="story-detail-section">
        <h4>Activity</h4>
        <div class="story-timeline">
          <div class="timeline-item">
            <i class="fas fa-plus-circle"></i>
            <div>
              <strong>Story created</strong>
              <span class="timestamp">${this.formatTime(story.createdAt)}</span>
            </div>
          </div>
          <div class="timeline-item">
            <i class="fas fa-edit"></i>
            <div>
              <strong>Last updated</strong>
              <span class="timestamp">${this.formatTime(story.updatedAt)}</span>
            </div>
          </div>
        </div>
      </div>
    `;

    // Add event listeners for inline editing
    this.setupModalEventListeners();
  }

  setupModalEventListeners() {
    const statusSelect = document.querySelector('.story-status-select');
    if (statusSelect) {
      statusSelect.addEventListener('change', async (e) => {
        const storyId = e.target.dataset.storyId;
        const newStatus = e.target.value;
        await this.updateStoryStatus(storyId, newStatus);
      });
    }
  }

  async updateStoryStatus(storyId, newStatus) {
    try {
      const response = await fetch(`/api/agile/stories/${storyId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus })
      });

      if (response.ok) {
        this.showSuccess('Story status updated');
        // Refresh the board to show the change
        await this.loadAgileData();
      } else {
        this.showError('Failed to update story status');
      }
    } catch (error) {
      console.error('Error updating story:', error);
      this.showError('Failed to update story status');
    }
  }

  closeModal(modal) {
    modal.classList.remove('show');
    
    // Wait for animation to complete before hiding
    setTimeout(() => {
      modal.style.display = 'none';
    }, 500); // Match the transition duration
  }

  closeStoryModal() {
    const modal = document.getElementById('storyDetailModal');
    this.closeModal(modal);
    
    // Clear content after closing
    setTimeout(() => {
      document.getElementById('storyDetailContent').innerHTML = '';
    }, 500);
  }

  isModalOpen() {
    const modal = document.getElementById('storyDetailModal');
    return modal && modal.classList.contains('show');
  }

  getInitials(name) {
    if (!name || name === 'Unassigned') return 'UN';
    return name.split(' ').map(n => n[0]).join('').toUpperCase();
  }

  // Epic Management Methods
  async loadEpicsData() {
    try {
      // Load all epics
      const epicsResponse = await fetch('/api/agile/epics?limit=100');
      if (epicsResponse.ok) {
        const epicsData = await epicsResponse.json();
        const epics = epicsData.data.epics || [];
        
        this.updateEpicStats(epics);
        this.renderEpicCards(epics);
        this.updateEpicCharts(epics);
      }
    } catch (error) {
      console.error('Error loading epics data:', error);
      this.showError('Failed to load epics data');
    }
  }

  updateEpicStats(epics) {
    const totalEpics = epics.length;
    const activeEpics = epics.filter(e => e.status === 'active').length;
    
    // Calculate total stories across all epics
    let totalStories = 0;
    let totalProgress = 0;
    
    epics.forEach(epic => {
      const storyCount = epic.storyIds ? epic.storyIds.length : 0;
      totalStories += storyCount;
      totalProgress += epic.progress || 0;
    });
    
    const avgProgress = totalEpics > 0 ? Math.round(totalProgress / totalEpics) : 0;
    
    // Update stats in UI
    document.getElementById('totalEpics').textContent = totalEpics;
    document.getElementById('activeEpics').textContent = activeEpics;
    document.getElementById('totalStories').textContent = totalStories;
    document.getElementById('avgProgress').textContent = `${avgProgress}%`;
  }

  renderEpicCards(epics) {
    const epicsGrid = document.getElementById('epicsGrid');
    
    if (epics.length === 0) {
      epicsGrid.innerHTML = `
        <div class="loading-state">
          <i class="fas fa-folder-open"></i>
          <p>No epics found. Create your first epic to get started!</p>
        </div>
      `;
      return;
    }
    
    epicsGrid.innerHTML = epics.map(epic => this.createEpicCard(epic)).join('');
    
    // Setup click handlers for epic cards
    this.setupEpicCardListeners();
  }

  createEpicCard(epic) {
    const storyCount = epic.storyIds ? epic.storyIds.length : 0;
    const completedStories = epic.completedStories || 0;
    const progress = epic.progress || 0;
    
    return `
      <div class="epic-card" data-epic-id="${epic.id}" data-status="${epic.status}">
        <div class="epic-card-header">
          <h3 class="epic-title">${this.escapeHtml(epic.title)}</h3>
          <span class="epic-priority" data-priority="${epic.priority}">
            ${epic.priority}
          </span>
        </div>
        
        <p class="epic-description">${this.escapeHtml(epic.description)}</p>
        
        ${epic.goals && epic.goals.length > 0 ? `
          <div class="epic-goals">
            ${epic.goals.slice(0, 2).map(goal => `
              <div class="epic-goal">
                <i class="fas fa-bullseye"></i>
                <span>${this.escapeHtml(goal)}</span>
              </div>
            `).join('')}
            ${epic.goals.length > 2 ? `<small>+${epic.goals.length - 2} more goals</small>` : ''}
          </div>
        ` : ''}
        
        <div class="epic-progress">
          <div class="epic-progress-bar">
            <div class="epic-progress-fill" style="width: ${progress}%"></div>
          </div>
          <div class="epic-progress-text">
            <span>${completedStories}/${storyCount} stories</span>
            <span>${progress}%</span>
          </div>
        </div>
        
        <div class="epic-stats-row">
          <div class="epic-stat">
            <div class="epic-stat-value">${storyCount}</div>
            <div class="epic-stat-label">Stories</div>
          </div>
          <div class="epic-stat">
            <div class="epic-stat-value">${epic.status}</div>
            <div class="epic-stat-label">Status</div>
          </div>
          <div class="epic-stat">
            <div class="epic-stat-value">${epic.owner || 'Unassigned'}</div>
            <div class="epic-stat-label">Owner</div>
          </div>
        </div>
      </div>
    `;
  }

  setupEpicCardListeners() {
    const epicCards = document.querySelectorAll('.epic-card');
    epicCards.forEach(card => {
      card.addEventListener('click', (e) => {
        e.preventDefault();
        e.stopPropagation();
        const epicId = card.dataset.epicId;
        if (epicId) {
          this.showEpicDetails(epicId);
        }
      });
    });

    // Setup filter dropdown
    const epicFilter = document.getElementById('epicFilter');
    if (epicFilter) {
      epicFilter.addEventListener('change', (e) => {
        this.filterEpics(e.target.value);
      });
    }

    // Setup create epic button
    const createEpicBtn = document.getElementById('createEpicBtn');
    if (createEpicBtn) {
      createEpicBtn.addEventListener('click', () => {
        this.showCreateEpicModal();
      });
    }
  }

  async showEpicDetails(epicId) {
    try {
      // Fetch epic details with stories
      const response = await fetch(`/api/agile/epic/${epicId}`);
      if (!response.ok) throw new Error('Failed to fetch epic details');
      
      const data = await response.json();
      const epic = data.data;
      
      // Fetch stories for this epic
      const storiesResponse = await fetch(`/api/agile/stories?epicId=${epicId}`);
      const storiesData = await storiesResponse.json();
      const stories = storiesData.data.stories || [];
      
      // Show modal with epic details
      const modal = document.getElementById('epicDetailModal');
      const content = document.getElementById('epicDetailContent');
      
      content.innerHTML = this.renderEpicDetails(epic, stories);
      
      // Reset modal state and show with animation
      modal.style.display = '';
      modal.classList.remove('show');
      
      // Force reflow to ensure the modal is positioned before animation
      void modal.offsetHeight;
      
      // Show modal with animation
      requestAnimationFrame(() => {
        modal.classList.add('show');
      });
      
      // Setup modal close handlers
      this.setupEpicModalHandlers();
      
    } catch (error) {
      console.error('Error showing epic details:', error);
      this.showError('Failed to load epic details');
    }
  }

  renderEpicDetails(epic, stories) {
    const completedStories = stories.filter(s => s.status === 'done').length;
    const inProgressStories = stories.filter(s => s.status === 'in_progress').length;
    const todoStories = stories.filter(s => s.status === 'todo').length;
    
    return `
      <div class="epic-detail-header">
        <h1 class="epic-detail-title">${this.escapeHtml(epic.title)}</h1>
        <div class="epic-detail-meta">
          <div class="epic-detail-meta-item">
            <i class="fas fa-flag"></i>
            <span>${epic.priority} priority</span>
          </div>
          <div class="epic-detail-meta-item">
            <i class="fas fa-info-circle"></i>
            <span>${epic.status}</span>
          </div>
          <div class="epic-detail-meta-item">
            <i class="fas fa-user"></i>
            <span>${epic.owner || 'Unassigned'}</span>
          </div>
          <div class="epic-detail-meta-item">
            <i class="fas fa-calendar"></i>
            <span>Created ${this.formatDate(epic.createdAt)}</span>
          </div>
        </div>
      </div>
      
      <div class="epic-detail-section">
        <h3>Description</h3>
        <p>${this.escapeHtml(epic.description)}</p>
      </div>
      
      ${epic.goals && epic.goals.length > 0 ? `
        <div class="epic-detail-section">
          <h3>Goals</h3>
          <ul class="epic-goals-list">
            ${epic.goals.map(goal => `
              <li><i class="fas fa-bullseye"></i> ${this.escapeHtml(goal)}</li>
            `).join('')}
          </ul>
        </div>
      ` : ''}
      
      <div class="epic-detail-section">
        <h3>Progress Overview</h3>
        <div class="epic-progress-stats">
          <div class="progress-stat">
            <div class="progress-value">${completedStories}</div>
            <div class="progress-label">Completed</div>
          </div>
          <div class="progress-stat">
            <div class="progress-value">${inProgressStories}</div>
            <div class="progress-label">In Progress</div>
          </div>
          <div class="progress-stat">
            <div class="progress-value">${todoStories}</div>
            <div class="progress-label">To Do</div>
          </div>
        </div>
        <div class="epic-progress">
          <div class="epic-progress-bar">
            <div class="epic-progress-fill" style="width: ${epic.progress || 0}%"></div>
          </div>
          <div class="epic-progress-text">
            <span>Overall Progress</span>
            <span>${epic.progress || 0}%</span>
          </div>
        </div>
      </div>
      
      <div class="epic-detail-section">
        <h3>Stories (${stories.length})</h3>
        <div class="epic-stories-list">
          ${stories.length > 0 ? stories.map(story => `
            <div class="epic-story-item" data-story-id="${story.id}">
              <div class="epic-story-info">
                <div class="epic-story-title">${this.escapeHtml(story.title)}</div>
                <div class="epic-story-meta">
                  <span><i class="fas fa-chart-line"></i> ${story.storyPoints} points</span>
                  <span><i class="fas fa-flag"></i> ${story.priority}</span>
                  ${story.assignee ? `<span><i class="fas fa-user"></i> ${story.assignee}</span>` : ''}
                </div>
              </div>
              <span class="epic-story-status" data-status="${story.status}">
                ${story.status.replace(/_/g, ' ')}
              </span>
            </div>
          `).join('') : '<p>No stories assigned to this epic yet.</p>'}
        </div>
      </div>
      
      ${epic.metadata ? `
        <div class="epic-detail-section">
          <h3>Additional Information</h3>
          <div class="epic-metadata">
            ${epic.metadata.businessValue ? `
              <div class="metadata-item">
                <strong>Business Value:</strong> ${this.escapeHtml(epic.metadata.businessValue)}
              </div>
            ` : ''}
            ${epic.metadata.targetUsers ? `
              <div class="metadata-item">
                <strong>Target Users:</strong> ${this.escapeHtml(epic.metadata.targetUsers)}
              </div>
            ` : ''}
            ${epic.metadata.risks ? `
              <div class="metadata-item">
                <strong>Risks:</strong> ${this.escapeHtml(epic.metadata.risks)}
              </div>
            ` : ''}
          </div>
        </div>
      ` : ''}
    `;
  }

  setupEpicModalHandlers() {
    const modal = document.getElementById('epicDetailModal');
    
    // Close button
    const closeBtn = document.getElementById('closeEpicModal');
    closeBtn.onclick = () => {
      this.closeModal(modal);
    };
    
    // Click outside modal
    modal.onclick = (e) => {
      if (e.target.classList.contains('modal-backdrop')) {
        this.closeModal(modal);
      }
    };
    
    // Story item clicks
    const storyItems = document.querySelectorAll('.epic-story-item');
    storyItems.forEach(item => {
      item.addEventListener('click', () => {
        const storyId = item.dataset.storyId;
        // Close epic modal and show story modal
        this.closeModal(modal);
        this.showStoryDetails(storyId);
      });
    });
  }

  filterEpics(filterValue) {
    const epicCards = document.querySelectorAll('.epic-card');
    
    epicCards.forEach(card => {
      const status = card.dataset.status;
      
      if (filterValue === 'all' || status === filterValue) {
        card.style.display = 'block';
      } else {
        card.style.display = 'none';
      }
    });
  }

  updateEpicCharts(epics) {
    // Epic Progress Overview Chart
    const progressCtx = document.getElementById('epicProgressChart');
    if (progressCtx && window.Chart) {
      const progressData = epics.map(e => ({
        name: e.title,
        progress: e.progress || 0
      })).sort((a, b) => b.progress - a.progress).slice(0, 10);
      
      new Chart(progressCtx, {
        type: 'bar',
        data: {
          labels: progressData.map(e => e.name),
          datasets: [{
            label: 'Progress %',
            data: progressData.map(e => e.progress),
            backgroundColor: 'rgba(25, 118, 210, 0.8)',
            borderColor: 'rgba(25, 118, 210, 1)',
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            y: {
              beginAtZero: true,
              max: 100
            }
          }
        }
      });
    }
    
    // Story Distribution Chart
    const distributionCtx = document.getElementById('storyDistributionChart');
    if (distributionCtx && window.Chart) {
      const statusCounts = {
        planned: epics.filter(e => e.status === 'planned').length,
        active: epics.filter(e => e.status === 'active').length,
        completed: epics.filter(e => e.status === 'completed').length,
        cancelled: epics.filter(e => e.status === 'cancelled').length
      };
      
      new Chart(distributionCtx, {
        type: 'doughnut',
        data: {
          labels: ['Planned', 'Active', 'Completed', 'Cancelled'],
          datasets: [{
            data: [
              statusCounts.planned,
              statusCounts.active,
              statusCounts.completed,
              statusCounts.cancelled
            ],
            backgroundColor: [
              'rgba(30, 136, 229, 0.8)',
              'rgba(67, 160, 71, 0.8)',
              'rgba(117, 117, 117, 0.8)',
              'rgba(229, 57, 53, 0.8)'
            ]
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false
        }
      });
    }
  }

  showCreateEpicModal() {
    // This would show a modal to create a new epic
    alert('Create Epic functionality would be implemented here');
  }

  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
}

// Initialize dashboard when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
  window.dashboard = new AtlasDashboard();
});

// Export for use in other scripts
window.AtlasDashboard = AtlasDashboard;