// packages/feature_game_colormatch/lib/controllers/colormatch_controller.dart

import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import '../models/colormatch_models.dart';

class ColorMatchController with ChangeNotifier {
  late ColorMatchDifficulty difficulty;
  late String userId;
  late String? userName;

  late MatchChallenge _currentChallenge;
  MatchChallenge get currentChallenge => _currentChallenge;

  int _currentRound = 0;
  int get currentRound => _currentRound;
  
  int _score = 0;
  int get score => _score;
  
  int _incorrectCount = 0;
  int get incorrectCount => _incorrectCount;

  Timer? _timer;
  int _secondsElapsed = 0;
  int get secondsElapsed => _secondsElapsed;

  bool _isGameCompleted = false;
  bool get isGameCompleted => _isGameCompleted;
  
  bool _showFeedback = false;
  bool get showFeedback => _showFeedback;
  
  bool _isLastAnswerCorrect = false;
  bool get isLastAnswerCorrect => _isLastAnswerCorrect;
  
  Timer? _challengeTimer;
  int _remainingChallengeTime = 0;
  int get remainingChallengeTime => _remainingChallengeTime;
  bool _isTimeOutFailure = false;
  bool get isTimeOutFailure => _isTimeOutFailure;
  
  MatchMode _currentMatchMode = MatchMode.matchColor;
  MatchMode get currentMatchMode => _currentMatchMode;

  final Random _random = Random();
  
  // 🔽 [🔥 신규] 3가지 목표 중 하나를 랜덤으로 반환
  MatchMode _getRandomMatchMode() {
    final modes = MatchMode.values;
    return modes[_random.nextInt(modes.length)];
  }
  
  // 🔽 [🔥 신규] MatchColor 리스트에서 이름으로 색상 객체를 찾는 헬퍼
  MatchColor _getMatchColorByName(String name, List<MatchColor> colors) {
    return colors.firstWhere((c) => c.name == name);
  }

  void setUserInfo(String userId, String? userName) {
    this.userId = userId;
    this.userName = userName;
  }

  void startNewGame(ColorMatchDifficulty level) {
    difficulty = level;
    // ... (상태 초기화 로직은 이전과 동일) ...
    _currentRound = 0;
    _score = 0;
    _incorrectCount = 0;
    _isGameCompleted = false;
    _secondsElapsed = 0;
    _showFeedback = false;
    _isTimeOutFailure = false;
    _currentMatchMode = MatchMode.matchColor;
    
    _generateNextChallenge();
    _startTimer();
    notifyListeners();
  }
  
  void restartGame() {
    startNewGame(difficulty);
  }
  
  void _startTimer() {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      _secondsElapsed++;
      notifyListeners();
    });
  }

  void _startChallengeTimer() {
    _challengeTimer?.cancel();
    if (difficulty.timeLimitSeconds <= 0) return;

    _remainingChallengeTime = difficulty.timeLimitSeconds;
    
    _challengeTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_remainingChallengeTime <= 0) {
        _challengeTimer?.cancel();
        _handleTimeOut();
      } else {
        _remainingChallengeTime--;
        notifyListeners();
      }
    });
  }

  void _handleTimeOut() {
    if (_isGameCompleted || _showFeedback) return;
    _challengeTimer?.cancel();
    _currentRound++;
    _incorrectCount++;
    _isLastAnswerCorrect = false;
    _isTimeOutFailure = true;
    _showFeedback = true;
    notifyListeners();
    _completeRoundSequence();
  }

  // 🔽 [🔥 핵심 수정] 다음 문제 생성 로직 (배경색 및 3중 목표)
  void _generateNextChallenge() {
    final colors = difficulty.colorSet;
    final bool enableStroop = difficulty.enableStroopEffect;
    
    // 1. 세 가지 주요 색상 요소 선택
    final MatchColor colorMeaning = colors[_random.nextInt(colors.length)]; // 단어의 의미 (정답 후보 1)
    final MatchColor colorText = colors[_random.nextInt(colors.length)];    // 텍스트의 실제 색상 (정답 후보 2)
    final MatchColor colorBackground = colors[_random.nextInt(colors.length)]; // 배경색 (정답 후보 3)
    
    String displayedWord = colorMeaning.name;
    Color textColor = colorText.color;
    Color finalTargetColor;
    
    if (enableStroop) {
      // 2. Lv 5-6: Stroop ON (MatchColor/MatchWord 50% 전환)
      if (difficulty.levelIndex < 7) {
        _currentMatchMode = _random.nextBool() ? MatchMode.matchColor : MatchMode.matchWord;
      } 
      // 3. Lv 7 이상: 3가지 목표 중 무작위 선택
      else {
        _currentMatchMode = _getRandomMatchMode();
      }
      
      // 4. 최종 정답 색상 결정
      switch (_currentMatchMode) {
        case MatchMode.matchColor:
          finalTargetColor = textColor;
          break;
        case MatchMode.matchWord:
          finalTargetColor = colorMeaning.color;
          break;
        case MatchMode.matchBackground:
          finalTargetColor = colorBackground.color;
          break;
      }
      
      // 인지 충돌 유도: 텍스트 색상과 단어의 의미가 50% 확률로 다르게 설정
      if (_random.nextBool()) {
          final List<Color> availableTextColors = colors.map((c) => c.color).where((c) => c != colorMeaning.color).toList();
          if (availableTextColors.isNotEmpty) {
             textColor = availableTextColors[_random.nextInt(availableTextColors.length)];
          }
      }
      
    } else {
      // Lv 1-4: Stroop OFF (항상 텍스트 색상 매칭, 단어와 색상 일치)
      _currentMatchMode = MatchMode.matchColor;
      displayedWord = colorMeaning.name;
      textColor = colorMeaning.color;
      finalTargetColor = textColor;
    }
    
    _currentChallenge = MatchChallenge(
      displayedWord: displayedWord,
      textColor: textColor,
      backgroundColor: colorBackground.color, // 👈 [추가]
      targetColor: finalTargetColor,
    );
    
    _startChallengeTimer();
  }
  
  // 🔽 정답 확인 및 지연 로직 (이전과 동일)
  void checkAnswer(Color selectedColor) {
    if (_isGameCompleted || _showFeedback) return;
    
    _challengeTimer?.cancel();
    
    final bool isCorrect = selectedColor == _currentChallenge.targetColor;
    
    _currentRound++;
    
    if (isCorrect) {
      _score++;
    } else {
      _incorrectCount++;
    }
    
    _isTimeOutFailure = false;
    _showFeedback = true;
    _isLastAnswerCorrect = isCorrect;
    notifyListeners();
    
    _completeRoundSequence();
  }

  void _completeRoundSequence() {
    Future.delayed(const Duration(milliseconds: 500), () {
      if (_currentRound >= difficulty.totalRounds) {
        _isGameCompleted = true;
        _timer?.cancel();
      } else {
        _showFeedback = false;
        _isTimeOutFailure = false;
        _generateNextChallenge();
      }
      notifyListeners();
    });
  }


  @override
  void dispose() {
    _timer?.cancel();
    _challengeTimer?.cancel();
    super.dispose();
  }
}