/**
 * @moduleName: QuizContent (Refactored Main Orchestrator)
 * @version: 3.0.0
 * @since: 2025-07-26
 * @lastUpdated: 2025-07-26
 * @projectSummary: Enhanced MCP Quiz Server - Modular Quiz Content Orchestrator
 * @techStack: TypeScript, Component Architecture, Event-Driven Design
 * @dependency: Component, EventManagement, AnswerHandler, NavigationController
 * @interModuleDependency: Coordinates all quiz sub-components with proper lifecycle management
 * @requirementsTraceability:
 *   {@link Requirements.REQ_UI_002} (Dual View Mode System - Quiz Orchestrator)
 *   {@link Requirements.REQ_EDU_001} (Educational Feedback System)
 *   {@link Requirements.REQ_ARCH_002} (Service Boundary Enforcement)
 *   {@link Requirements.REQ_PERF_007} (Memory Management and Cleanup)
 *   {@link Requirements.REQ_A11Y_001} (Screen Reader Compatibility)
 * @briefDescription: Main quiz orchestrator managing view modes, rendering, and component coordination
 * @methods: render, renderQuiz, renderSingleQuestionMode, renderAllQuestionsMode, cleanup
 * @contributors: GitHub Copilot
 * @examples:
 *   - const quizContent = new QuizContent(); quizContent.render();
 * @vulnerabilitiesAssessment: Event-driven architecture with proper cleanup, no sensitive data exposure
 */

import { QuizProgressManager } from '../services/QuizProgressManager';
import { SettingsService } from '../services/SettingsService';
import { TimerService } from '../services/TimerService';
import { AppStore } from '../store/AppStore';
import { AppState, Question, Quiz, ViewMode } from '../types/index';
import { DOMUtils } from '../utils/index';
import { Component } from './Component';
import { AnswerHandler } from './quiz/AnswerHandler';
import { EventManagement } from './quiz/EventManagement';
import { NavigationController } from './quiz/NavigationController';

export class QuizContent extends Component {
  private store: AppStore;
  private settingsService: SettingsService;
  private timerService: TimerService;
  private answerHandler: AnswerHandler;
  private navigationController: NavigationController;
  private progressManager: QuizProgressManager | null = null;
  private previousAnswers: Record<string, string> = {};
  private answerDebounceTimer: number | null = null; // FIX: Critical Gap 3 - Race condition prevention

  private welcomeScreen: HTMLElement;
  private quizContainer: HTMLElement;
  private submitButton: HTMLButtonElement;
  private unsubscribe: (() => void) | null = null;
  private timerUnsubscribe: (() => void) | null = null;
  private viewModeToggleSetup = false;

  constructor() {
    super('#quiz-content');
    this.store = AppStore.getInstance();
    this.settingsService = SettingsService.getInstance();
    this.timerService = TimerService.getInstance();

    // Initialize sub-components
    this.answerHandler = new AnswerHandler(this.store, this.settingsService);
    this.navigationController = new NavigationController(this.store, this.settingsService);

    // Get DOM elements
    this.welcomeScreen = document.querySelector('#welcome-screen') as HTMLElement;
    this.quizContainer = document.querySelector('#quiz-container') as HTMLElement;
    this.submitButton = document.querySelector('#submit-button') as HTMLButtonElement;

    // Set up event listeners for component communication
    this.setupComponentEvents();
  }

  /**
   * Set up inter-component communication events
   */
  private setupComponentEvents(): void {
    document.addEventListener('quiz:render-question', (e: Event) => {
      const customEvent = e as CustomEvent;
      const { questionIndex } = customEvent.detail;
      this.renderCurrentQuestion(questionIndex);
    });

    document.addEventListener('quiz:show-results', () => {
      this.showResults();
    });

    // Listen for quiz completion from progress manager
    document.addEventListener('quiz:completed', (e: Event) => {
      const customEvent = e as CustomEvent;
      console.log('🎉 Quiz completed via auto-advance:', customEvent.detail);
      this.showResults();
    });
  }

  render(): void {
    if (!this.element) return;

    const state = this.store.getState();

    if (state.currentQuiz) {
      this.renderQuiz(state.currentQuiz, state.userAnswers);
    } else {
      this.renderWelcome();
    }

    // Set up view mode toggle (only once)
    if (!this.viewModeToggleSetup) {
      this.setupViewModeToggle();
      this.viewModeToggleSetup = true;
    }

    // Subscribe to store changes
    if (!this.unsubscribe) {
      this.unsubscribe = this.store.subscribe((newState: AppState) => {
        this.handleStateChange(newState);
      });
    }

    // Subscribe to timer if available
    if (!this.timerUnsubscribe && this.timerService) {
      this.timerUnsubscribe = this.timerService.subscribe(() => {
        this.updateTimerDisplay();
      });
    }

    // Listen for timer settings changes from QuizStartModal
    window.addEventListener('timerSettingsChanged', (event: Event) => {
      const customEvent = event as CustomEvent;
      console.log('🔄 Timer settings changed, updating display');
      this.updateTimerDisplay();

      // Auto-start timer if enabled (MODERNIZED)
      if (customEvent.detail?.useTimer) {
        this.autoStartTimerIfEnabled();
      }
    });
  }

  /**
   * Handle store state changes with debounced answer detection (FIX: Critical Gap 3)
   */
  private handleStateChange(state: AppState): void {
    if (state.currentQuiz) {
      this.renderQuiz(state.currentQuiz, state.userAnswers);

      // Check for new answers with debouncing to prevent race conditions
      if (this.progressManager) {
        const newAnswers: Array<{ questionId: string; answer: string }> = [];

        for (const [questionId, answer] of Object.entries(state.userAnswers)) {
          if (this.previousAnswers[questionId] !== answer) {
            newAnswers.push({ questionId, answer });
          }
        }

        if (newAnswers.length > 0) {
          // Clear existing debounce timer
          if (this.answerDebounceTimer) {
            window.clearTimeout(this.answerDebounceTimer);
          }

          // Debounce answer processing to prevent race conditions
          this.answerDebounceTimer = window.setTimeout(() => {
            console.log('📝 Processing debounced answers:', newAnswers);

            // Process each new answer
            newAnswers.forEach(({ questionId, answer }) => {
              this.progressManager?.handleAnswerSelection(questionId, answer);
            });

            this.answerDebounceTimer = null;
          }, 150); // 150ms debounce - enough to prevent double-firing, fast enough for UX
        }
      }

      // Update previous answers
      this.previousAnswers = { ...state.userAnswers };
    } else {
      this.renderWelcome();
    }
  }

  /**
   * Auto-start timer if enabled (REQ-UI-012) - MODERNIZED
   */
  private autoStartTimerIfEnabled(): void {
    const settings = this.settingsService.getSettings();

    // Simple check: if timer is enabled, start it automatically
    if (settings.quiz.useTimer && this.timerService) {
      const timerState = this.timerService.getState();

      // Only start if timer is not already running
      if (!timerState.isRunning) {
        console.log('🚀 Auto-starting timer (modern single-setting approach)');
        this.timerService.autoStartIfEnabled(this.settingsService);
      }
    }
  }

  /**
   * Initialize progress manager for auto-advance (REQ-UI-011)
   */
  private initializeProgressManager(quiz: Quiz): void {
    // Clean up existing progress manager
    if (this.progressManager) {
      this.progressManager.destroy();
    }

    // Create new progress manager
    this.progressManager = new QuizProgressManager(
      quiz,
      this.settingsService.getSettings(),
      this.navigationController,
      null // feedbackManager - will be integrated later
    );

    console.log('📊 Progress manager initialized for quiz:', quiz.id);
  }

  /**
   * Render the welcome screen
   */
  private renderWelcome(): void {
    if (this.welcomeScreen) {
      this.welcomeScreen.style.display = 'block';
    }
    if (this.quizContainer) {
      this.quizContainer.style.display = 'none';
    }
    console.log('📋 Welcome screen displayed');
  }

  /**
   * Main quiz rendering method
   */
  private renderQuiz(quiz: Quiz, userAnswers: Record<string, string>): void {
    if (!quiz) return;

    // Hide welcome, show quiz
    if (this.welcomeScreen) {
      this.welcomeScreen.style.display = 'none';
    }
    if (this.quizContainer) {
      this.quizContainer.style.display = 'block';
    }

    // Initialize progress manager for auto-advance (REQ-UI-011)
    this.initializeProgressManager(quiz);

    // Auto-start timer if enabled (REQ-UI-012)
    this.autoStartTimerIfEnabled();

    const state = this.store.getState();

    // Render based on view mode
    if (state.ui.viewMode === 'single') {
      this.renderSingleQuestionMode(quiz, userAnswers);
    } else {
      this.renderAllQuestionsMode(quiz, userAnswers);
    }

    // Update timer display if in timed mode
    this.updateTimerDisplay();

    console.log(`🎯 Quiz rendered in ${state.ui.viewMode} mode`);
  }

  /**
   * Render single question mode (CRITICAL: Fixed infinite recursion)
   */
  private renderSingleQuestionMode(quiz: Quiz, userAnswers: Record<string, string>): void {
    const currentIndex = this.navigationController.getCurrentQuestionIndex();
    const question = quiz.questions[currentIndex];

    if (!question) {
      console.error('🚨 No question found at index:', currentIndex);
      return;
    }

    const isLastQuestion = this.navigationController.isLastQuestion();
    const isAnswered = userAnswers[question.id] !== undefined;
    const settings = this.settingsService.getSettings();

    // Generate question HTML
    const questionHtml = this.renderQuestion(question, currentIndex, userAnswers);

    // Generate action button HTML with smart submit logic (REQ-UI-013)
    let actionButtonHtml = '';
    const shouldShowButton = this.shouldShowSubmitButton(isAnswered, isLastQuestion, settings);

    if (isLastQuestion) {
      actionButtonHtml = `
        <div class="complete-quiz-container mt-6 text-center" style="${shouldShowButton ? '' : 'display: none;'}">
          <button id="complete-quiz-btn" class="bg-green-600 hover:bg-green-700 text-white font-medium py-3 px-8 rounded-lg transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 shadow-lg">
            <span class="flex items-center justify-center">
              <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
              </svg>
              Complete Quiz
            </span>
          </button>
        </div>
      `;
    } else if (settings.ui.showContinueButton) {
      actionButtonHtml = `
        <div class="continue-button-container mt-6 text-center" style="${shouldShowButton ? '' : 'display: none;'}">
          <button id="continue-btn" class="bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-6 rounded-lg transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
            <span class="flex items-center justify-center">
              <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
              </svg>
              Continue
            </span>
          </button>
        </div>
      `;
    }

    // Update DOM
    this.quizContainer.innerHTML = `
      <div class="single-question-view">
        <div class="progress-indicator text-center mb-4 md:mb-6">
          <span class="text-lg font-medium text-gray-700">
            Question ${currentIndex + 1} of ${quiz.questions.length}
          </span>
          <div class="w-full bg-gray-200 rounded-full h-2 mt-2">
            <div class="bg-blue-600 h-2 rounded-full transition-all duration-300"
                 style="width: ${((currentIndex + 1) / quiz.questions.length) * 100}%"></div>
          </div>
        </div>
        ${questionHtml}
        ${actionButtonHtml}
      </div>
    `;

    // CRITICAL FIX: Set up components with proper cleanup
    this.setupComponentsForCurrentView();
  }

  /**
   * Render all questions mode
   */
  private renderAllQuestionsMode(quiz: Quiz, userAnswers: Record<string, string>): void {
    const questionsHtml = quiz.questions
      .map((question, index) => this.renderQuestion(question, index, userAnswers))
      .join('');

    this.quizContainer.innerHTML = `<div class="all-questions-view space-y-4 md:space-y-6">${questionsHtml}</div>`;

    // Set up components for all questions view
    this.setupComponentsForCurrentView();
  }

  /**
   * Set up sub-components for current view (CRITICAL: Prevents infinite recursion)
   */
  private setupComponentsForCurrentView(): void {
    // Set up answer handling
    this.answerHandler.setupAnswerHandling(this.quizContainer);

    // Set up navigation (this fixes the infinite recursion bug)
    this.navigationController.setupNavigation();

    console.log('✅ All components set up for current view');
  }

  /**
   * Render a single question
   */
  private renderQuestion(
    question: Question,
    index: number,
    userAnswers: Record<string, string>
  ): string {
    const settings = this.settingsService.getSettings();
    const state = this.store.getState();
    const isSingleMode = state.ui.viewMode === 'single';

    // Determine which UI to use based on mode and settings
    const useClickableCards = isSingleMode && settings.ui.clickToSelectCards;
    const useInstantSubmission = settings.quiz.instantSubmission;

    const optionsHtml = question.options
      .map(option => {
        const isSelected = userAnswers[question.id] === option;

        if (useInstantSubmission) {
          return this.renderInstantSubmissionCard(question, option, isSelected);
        } else if (useClickableCards) {
          return this.renderClickableCard(question, option, isSelected);
        } else {
          return this.renderTraditionalRadio(question, option, isSelected);
        }
      })
      .join('');

    return `
      <div class="question-block mb-6" data-question-id="${question.id}">
        <h3 class="text-xl font-semibold mb-4 text-gray-800 dark:text-gray-200">
          ${DOMUtils.escapeHtml(question.question)}
        </h3>
        <div class="options-container space-y-3">
          ${optionsHtml}
        </div>
      </div>
    `;
  }

  /**
   * Render instant submission card
   */
  private renderInstantSubmissionCard(
    question: Question,
    option: string,
    isSelected: boolean
  ): string {
    return `
      <div class="quiz-option-card cursor-pointer p-4 rounded-xl border-2 transition-all duration-300 transform hover:scale-[1.02] hover:shadow-lg ${
        isSelected
          ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20 shadow-md'
          : 'border-gray-200 dark:border-gray-600 hover:border-blue-300 dark:hover:border-blue-500'
      }"
      data-question-id="${question.id}"
      data-answer="${DOMUtils.escapeHtml(option)}"
      role="button"
      tabindex="0"
      aria-pressed="${isSelected}">
        <div class="flex items-center justify-between">
          <span class="text-gray-900 dark:text-gray-100 font-medium">${DOMUtils.escapeHtml(option)}</span>
          <div class="answer-indicator w-6 h-6 rounded-full border-2 transition-all duration-200 ${
            isSelected ? 'border-blue-500 bg-blue-500' : 'border-gray-300 dark:border-gray-500'
          }">
            ${isSelected ? '<div class="w-2 h-2 bg-white rounded-full mx-auto mt-1"></div>' : ''}
          </div>
        </div>
      </div>
    `;
  }

  /**
   * Render clickable card (non-instant)
   */
  private renderClickableCard(question: Question, option: string, isSelected: boolean): string {
    return `
      <div class="quiz-option-card cursor-pointer p-4 rounded-xl border-2 transition-all duration-300 ${
        isSelected
          ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20 shadow-md'
          : 'border-gray-200 dark:border-gray-600 hover:border-blue-300 dark:hover:border-blue-500'
      }"
      data-question-id="${question.id}"
      data-answer="${DOMUtils.escapeHtml(option)}"
      role="button"
      tabindex="0"
      aria-pressed="${isSelected}">
        <div class="flex items-center justify-between">
          <span class="text-gray-900 dark:text-gray-100 font-medium">${DOMUtils.escapeHtml(option)}</span>
          <div class="answer-indicator w-6 h-6 rounded-full border-2 transition-all duration-200 ${
            isSelected ? 'border-blue-500 bg-blue-500' : 'border-gray-300 dark:border-gray-500'
          }">
            ${isSelected ? '<div class="w-2 h-2 bg-white rounded-full mx-auto mt-1"></div>' : ''}
          </div>
        </div>
      </div>
    `;
  }

  /**
   * Render traditional radio button
   */
  private renderTraditionalRadio(question: Question, option: string, isSelected: boolean): string {
    return `
      <label class="flex items-center p-3 rounded-lg border border-gray-200 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer">
        <input type="radio" name="${question.id}" value="${DOMUtils.escapeHtml(option)}"
               ${isSelected ? 'checked' : ''}
               class="mr-3 text-blue-600 focus:ring-blue-500">
        <span class="text-gray-900 dark:text-gray-100">${DOMUtils.escapeHtml(option)}</span>
      </label>
    `;
  }

  /**
   * Render current question in single mode
   */
  private renderCurrentQuestion(questionIndex: number): void {
    this.navigationController.setCurrentQuestionIndex(questionIndex);
    const state = this.store.getState();
    if (state.currentQuiz) {
      this.renderQuiz(state.currentQuiz, state.userAnswers);
    }
  }

  /**
   * Show quiz results
   */
  private showResults(): void {
    // This will be handled by a ResultsModal component
    console.log('🎉 Showing quiz results');
  }

  /**
   * Set up view mode toggle (existing functionality)
   */
  private setupViewModeToggle(): void {
    const singleModeBtn = document.getElementById('view-mode-single');
    const listModeBtn = document.getElementById('view-mode-list');

    if (singleModeBtn && listModeBtn) {
      EventManagement.addListener(
        singleModeBtn,
        'click',
        () => this.setViewMode('single'),
        'view-mode-single'
      );

      EventManagement.addListener(
        listModeBtn,
        'click',
        () => this.setViewMode('list'),
        'view-mode-list'
      );

      console.log('🔗 View mode toggle set up successfully');
    } else {
      console.warn('❌ View mode buttons not found:', {
        singleModeBtn: !!singleModeBtn,
        listModeBtn: !!listModeBtn,
      });
    }
  }

  /**
   * Set view mode
   */
  private setViewMode(mode: ViewMode): void {
    this.store.setViewMode(mode);
    console.log(`👁️ View mode changed to: ${mode}`);
  }

  /**
   * Update timer display (MODERNIZED)
   */
  private updateTimerDisplay(): void {
    const timerStatusElement = document.getElementById('timer-status');
    const timerCountdownElement = document.getElementById('timer-countdown');

    if (!timerStatusElement || !timerCountdownElement) return;

    const settings = this.settingsService.getSettings();
    const useTimer = settings.quiz?.useTimer || false;

    if (!useTimer) {
      timerStatusElement.textContent = 'Not configured';
      timerCountdownElement.classList.add('hidden');
      return;
    }

    if (this.timerService) {
      const timerState = this.timerService.getState();

      if (timerState.isRunning) {
        timerStatusElement.textContent = 'Running';
        timerCountdownElement.textContent = this.formatTime(timerState.timeRemaining);
        timerCountdownElement.classList.remove('hidden');
      } else {
        timerStatusElement.textContent = 'Ready to start';
        timerCountdownElement.textContent = this.formatTime(timerState.totalTime);
        timerCountdownElement.classList.remove('hidden');
      }
    } else {
      timerStatusElement.textContent = 'Enabled';
      timerCountdownElement.classList.add('hidden');
    }
  }

  /**
   * Smart submit button logic (REQ-UI-013)
   */
  private shouldShowSubmitButton(
    isAnswered: boolean,
    isLastQuestion: boolean,
    settings: any
  ): boolean {
    const state = this.store.getState();

    // In single question mode, use existing logic
    if (state.ui.viewMode === 'single') {
      return isAnswered;
    }

    // In all questions mode, use smart logic
    const quiz = state.currentQuiz;
    if (!quiz) return false;

    const answeredCount = Object.keys(state.userAnswers).length;
    const totalQuestions = quiz.questions.length;
    const completionRate = answeredCount / totalQuestions;

    // Smart submit logic: Show button when user has made significant progress
    return (
      completionRate >= 0.7 || // 70% complete
      answeredCount === totalQuestions || // All answered
      settings.quiz.smartSubmitLogic === false
    ); // User disabled smart logic
  }

  /**
   * Format time for display
   */
  private formatTime(seconds: number): string {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  }

  /**
   * Clean up component and sub-components
   */
  destroy(): void {
    // Clean up subscriptions
    if (this.unsubscribe) {
      this.unsubscribe();
      this.unsubscribe = null;
    }

    if (this.timerUnsubscribe) {
      this.timerUnsubscribe();
      this.timerUnsubscribe = null;
    }

    // Clean up debounce timer (FIX: Critical Gap 3 - Memory leak prevention)
    if (this.answerDebounceTimer) {
      window.clearTimeout(this.answerDebounceTimer);
      this.answerDebounceTimer = null;
    }

    // Clean up progress manager
    if (this.progressManager) {
      this.progressManager.destroy();
      this.progressManager = null;
    }

    // Clean up sub-components
    this.answerHandler.cleanup();
    this.navigationController.cleanup();

    // Clean up all event listeners
    EventManagement.cleanup();

    console.log('🧹 QuizContent cleanup completed');
  }
}
