// ===== HALLOWEEN MEMORY MATCH GAME - ARTICULATE STORYLINE OPTIMIZED =====

(() => {
  'use strict';

  // === GAME CONFIGURATION ===
  const HALLOWEEN_EMOJIS = [
    '🎃', '👻', '🕸️', '🕷️', '💀', '🧛', 
    '🧙', '🧟', '🍭', '🕯️', '⚰️', '🪦', 
    '🦇', '🧹', '🍬', '🧛‍♀️', '🔮', '🌙',
    '⭐', '🕸️', '🦴', '🍎', '🥀', '🖤'
  ];

  const DIFFICULTY_CONFIG = {
    6: { name: 'Easy', timeLimit: 90, scoreMultiplier: 1 },
    8: { name: 'Medium', timeLimit: 75, scoreMultiplier: 1.5 },
    12: { name: 'Hard', timeLimit: 60, scoreMultiplier: 2 }
  };

  // === GAME STATE ===
  let gameState = {
    selectedPairs: 8,
    cards: [],
    flippedCards: [],
    matchedPairs: 0,
    score: 0,
    timeLeft: 75,
    gameTimer: null,
    isGameActive: false,
    canFlip: true
  };

  // === DOM ELEMENTS ===
  const elements = {
    // Screens
    startScreen: document.getElementById('start-screen'),
    gameScreen: document.getElementById('game-screen'),
    completeScreen: document.getElementById('complete-screen'),
    
    // Start screen
    difficultyBtns: document.querySelectorAll('.difficulty-btn'),
    startBtn: document.getElementById('start-btn'),
    
    // Game screen
    memoryGrid: document.getElementById('memory-grid'),
    scoreEl: document.getElementById('score'),
    matchesEl: document.getElementById('matches'),
    totalPairsEl: document.getElementById('total-pairs'),
    timerEl: document.getElementById('timer'),
    gameMessage: document.getElementById('game-message'),
    resetBtn: document.getElementById('reset-btn'),
    
    // Complete screen
    completionTitle: document.getElementById('completion-title'),
    finalScore: document.getElementById('final-score'),
    timeRemaining: document.getElementById('time-remaining'),
    playAgainBtn: document.getElementById('play-again-btn')
  };

  // === UTILITY FUNCTIONS ===
  const utils = {
    shuffle: (array) => {
      const shuffled = [...array];
      for (let i = shuffled.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
      }
      return shuffled;
    },

    showScreen: (screenToShow) => {
      Object.values(elements).forEach(el => {
        if (el && el.classList && el.classList.contains('screen')) {
          el.classList.remove('active');
        }
      });
      screenToShow.classList.add('active');
    },

    updateDisplay: () => {
      elements.scoreEl.textContent = gameState.score;
      elements.matchesEl.textContent = gameState.matchedPairs;
      elements.totalPairsEl.textContent = gameState.selectedPairs;
      elements.timerEl.textContent = `${gameState.timeLeft}s`;
    },

    setMessage: (message, type = 'info') => {
      elements.gameMessage.textContent = message;
      elements.gameMessage.className = `message-${type}`;
    },

    calculateScore: (timeBonus = 0) => {
      const config = DIFFICULTY_CONFIG[gameState.selectedPairs];
      const baseScore = 100;
      const timeBonusScore = timeBonus * 2;
      return Math.floor((baseScore + timeBonusScore) * config.scoreMultiplier);
    }
  };

  // === AUDIO SYSTEM (Simple Web Audio) ===
  const audio = {
    context: null,
    
    init: () => {
      try {
        audio.context = new (window.AudioContext || window.webkitAudioContext)();
      } catch (e) {
        console.log('Web Audio not supported');
      }
    },

    playTone: (frequency, duration, type = 'sine') => {
      if (!audio.context) return;
      
      const oscillator = audio.context.createOscillator();
      const gainNode = audio.context.createGain();
      
      oscillator.connect(gainNode);
      gainNode.connect(audio.context.destination);
      
      oscillator.frequency.setValueAtTime(frequency, audio.context.currentTime);
      oscillator.type = type;
      
      gainNode.gain.setValueAtTime(0.1, audio.context.currentTime);
      gainNode.gain.exponentialRampToValueAtTime(0.01, audio.context.currentTime + duration);
      
      oscillator.start(audio.context.currentTime);
      oscillator.stop(audio.context.currentTime + duration);
    },

    playFlip: () => audio.playTone(800, 0.1),
    playMatch: () => audio.playTone(1200, 0.3),
    playError: () => audio.playTone(300, 0.5),
    playWin: () => {
      setTimeout(() => audio.playTone(523, 0.2), 0);
      setTimeout(() => audio.playTone(659, 0.2), 200);
      setTimeout(() => audio.playTone(784, 0.4), 400);
    }
  };

  // === CARD MANAGEMENT ===
  const cardManager = {
    createCard: (emoji, index) => {
      const card = document.createElement('div');
      card.className = 'memory-card';
      card.dataset.emoji = emoji;
      card.dataset.index = index;
      
      card.innerHTML = `
        <div class="card-inner">
          <div class="card-front"></div>
          <div class="card-back">${emoji}</div>
        </div>
      `;
      
      card.addEventListener('click', () => cardManager.handleCardClick(card));
      return card;
    },

    handleCardClick: (card) => {
      if (!gameState.canFlip || !gameState.isGameActive) return;
      if (card.classList.contains('flipped') || card.classList.contains('matched')) return;
      if (gameState.flippedCards.length >= 2) return;

      // Flip card
      card.classList.add('flipped');
      gameState.flippedCards.push(card);
      audio.playFlip();

      if (gameState.flippedCards.length === 2) {
        gameState.canFlip = false;
        setTimeout(() => cardManager.checkMatch(), 1000);
      }
    },

    checkMatch: () => {
      const [card1, card2] = gameState.flippedCards;
      const emoji1 = card1.dataset.emoji;
      const emoji2 = card2.dataset.emoji;

      if (emoji1 === emoji2) {
        // Match found!
        card1.classList.add('matched');
        card2.classList.add('matched');
        
        gameState.matchedPairs++;
        const matchScore = utils.calculateScore(gameState.timeLeft);
        gameState.score += matchScore;
        
        audio.playMatch();
        utils.setMessage(`Great match! +${matchScore} points`, 'success');
        
        // Check for game completion
        if (gameState.matchedPairs === gameState.selectedPairs) {
          gameManager.completeGame(true);
        }
      } else {
        // No match
        setTimeout(() => {
          card1.classList.remove('flipped');
          card2.classList.remove('flipped');
          card1.classList.add('card-error');
          card2.classList.add('card-error');
          
          setTimeout(() => {
            card1.classList.remove('card-error');
            card2.classList.remove('card-error');
          }, 600);
        }, 300);
        
        audio.playError();
        utils.setMessage('Try again!', 'error');
      }

      gameState.flippedCards = [];
      gameState.canFlip = true;
      utils.updateDisplay();
    },

    setupGrid: () => {
      const pairs = gameState.selectedPairs;
      const selectedEmojis = utils.shuffle(HALLOWEEN_EMOJIS).slice(0, pairs);
      const allCards = utils.shuffle([...selectedEmojis, ...selectedEmojis]);
      
      console.log(`Setting up grid for ${pairs} pairs (${allCards.length} total cards)`);
      
      // Set grid layout based on number of pairs
      let gridClass;
      if (pairs === 6) {
        gridClass = 'grid-3x4'; // 3 columns, 4 rows for 12 cards
      } else if (pairs === 8) {
        gridClass = 'grid-4x4'; // 4 columns, 4 rows for 16 cards
      } else if (pairs === 12) {
        gridClass = 'grid-4x6'; // 4 columns, 6 rows for 24 cards
      } else {
        gridClass = 'grid-4x4'; // fallback
      }
      
      elements.memoryGrid.className = gridClass;
      elements.memoryGrid.innerHTML = '';
      
      console.log(`Applied grid class: ${gridClass}`);
      
      allCards.forEach((emoji, index) => {
        const card = cardManager.createCard(emoji, index);
        elements.memoryGrid.appendChild(card);
      });
      
      console.log(`Created ${allCards.length} cards`);
    }
  };

  // === GAME MANAGEMENT ===
  const gameManager = {
    startGame: () => {
      const config = DIFFICULTY_CONFIG[gameState.selectedPairs];
      
      // Reset game state
      gameState = {
        ...gameState,
        matchedPairs: 0,
        score: 0,
        timeLeft: config.timeLimit,
        flippedCards: [],
        isGameActive: true,
        canFlip: true
      };

      // Setup UI
      cardManager.setupGrid();
      utils.updateDisplay();
      utils.setMessage(`Find all ${gameState.selectedPairs} pairs!`);
      utils.showScreen(elements.gameScreen);
      
      // Start timer
      gameManager.startTimer();
    },

    startTimer: () => {
      if (gameState.gameTimer) clearInterval(gameState.gameTimer);
      
      gameState.gameTimer = setInterval(() => {
        gameState.timeLeft--;
        utils.updateDisplay();
        
        if (gameState.timeLeft <= 10) {
          utils.setMessage(`Hurry! ${gameState.timeLeft} seconds left!`, 'warning');
        }
        
        if (gameState.timeLeft <= 0) {
          gameManager.completeGame(false);
        }
      }, 1000);
    },

    completeGame: (isWin) => {
      gameState.isGameActive = false;
      gameState.canFlip = false;
      clearInterval(gameState.gameTimer);
      
      if (isWin) {
        const timeBonus = gameState.timeLeft * 10;
        gameState.score += timeBonus;
        
        elements.completionTitle.textContent = '🎉 Spooktacular! 🎉';
        elements.finalScore.textContent = gameState.score;
        elements.timeRemaining.textContent = `${gameState.timeLeft}s`;
        
        audio.playWin();
        utils.setMessage('All pairs found!', 'success');
      } else {
        elements.completionTitle.textContent = '👻 Time\'s Up! 👻';
        elements.finalScore.textContent = gameState.score;
        elements.timeRemaining.textContent = '0s';
        
        utils.setMessage('Better luck next time!', 'error');
      }
      
      setTimeout(() => utils.showScreen(elements.completeScreen), 2000);
    },

    resetGame: () => {
      clearInterval(gameState.gameTimer);
      utils.showScreen(elements.startScreen);
    }
  };

  // === EVENT HANDLERS ===
  const eventHandlers = {
    init: () => {
      // Difficulty selection
      elements.difficultyBtns.forEach(btn => {
        btn.addEventListener('click', () => {
          elements.difficultyBtns.forEach(b => b.classList.remove('active'));
          btn.classList.add('active');
          gameState.selectedPairs = parseInt(btn.dataset.pairs);
        });
      });

      // Game controls
      elements.startBtn.addEventListener('click', gameManager.startGame);
      elements.resetBtn.addEventListener('click', gameManager.resetGame);
      elements.playAgainBtn.addEventListener('click', gameManager.resetGame);

      // Keyboard support
      document.addEventListener('keydown', (e) => {
        if (e.code === 'Space' && elements.startScreen.classList.contains('active')) {
          e.preventDefault();
          gameManager.startGame();
        }
        if (e.code === 'Escape') {
          gameManager.resetGame();
        }
      });

      // Initialize audio on first user interaction
      document.addEventListener('click', () => {
        if (!audio.context) audio.init();
      }, { once: true });
    }
  };

  // === INITIALIZATION ===
  const init = () => {
    console.log('🎃 Halloween Memory Match - Initializing...');
    
    // Set default difficulty
    gameState.selectedPairs = 8;
    
    // Initialize event handlers
    eventHandlers.init();
    
    // Show start screen
    utils.showScreen(elements.startScreen);
    
    console.log('✅ Game initialized successfully!');
  };

  // Start the game when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

})();