// EL3AB Puzzle Controller - Daily puzzles, streak, themes, rush mode

const Puzzles = {
  chess: null,
  currentPuzzle: null,
  puzzleQueue: [],
  puzzleSolution: [],
  solutionIndex: 0,
  playerRating: 1200,
  currentStreak: 0,
  bestStreak: 0,
  dailySolved: 0,
  mode: 'daily', // daily, streak, themes, rush
  selectedTheme: null,
  rushTimer: null,
  rushTimeLeft: 180, // 3 minutes
  rushCount: 0,
  isRushActive: false,
  isSolving: false,
  puzzleStartTime: 0,

  async init() {
    this.bindTabs();
    await this.loadStats();
    await this.loadDaily();
  },

  bindTabs() {
    document.querySelectorAll('#puzzle-tabs .tab').forEach(tab => {
      tab.addEventListener('click', () => {
        document.querySelectorAll('#puzzle-tabs .tab').forEach(t => t.classList.remove('active'));
        tab.classList.add('active');

        const tabId = tab.dataset.tab;
        document.querySelectorAll('.puzzle-tab-content').forEach(el => el.style.display = 'none');
        document.getElementById('tab-' + tabId).style.display = 'block';

        this.mode = tabId;

        // Hide board when switching tabs (unless already solving)
        if (!this.isSolving) {
          document.getElementById('puzzle-board-area').style.display = 'none';
        }
      });
    });

    // Theme cards
    document.querySelectorAll('.puzzle-theme-card').forEach(card => {
      card.addEventListener('click', () => {
        this.selectedTheme = card.dataset.theme;
        this.startThemePuzzles(this.selectedTheme);
      });
    });
  },

  async loadStats() {
    try {
      const data = await App.fetch('/api/puzzles?action=streak');
      if (data) {
        this.playerRating = data.puzzle_rating || 1200;
        this.currentStreak = data.puzzle_streak || 0;
        this.bestStreak = data.best_puzzle_streak || 0;
        this.updateStatsUI();
      }
    } catch (e) {}
  },

  updateStatsUI() {
    document.getElementById('puzzle-rating').textContent = this.playerRating;
    document.getElementById('puzzle-streak').textContent = this.currentStreak;
    document.getElementById('puzzle-best-streak').textContent = this.bestStreak;
  },

  async loadDaily() {
    try {
      const data = await App.fetch('/api/puzzles?action=daily');
      if (data && data.puzzles && data.puzzles.length > 0) {
        this.puzzleQueue = data.puzzles;
        this.updateDailyProgress();

        // Auto-start first unsolved daily puzzle
        if (this.dailySolved < this.puzzleQueue.length) {
          this.startPuzzle(this.puzzleQueue[this.dailySolved]);
        }
      } else {
        // No puzzles from server, use built-in fallback puzzles
        this.puzzleQueue = this.getFallbackPuzzles();
        this.startPuzzle(this.puzzleQueue[0]);
      }
    } catch (e) {
      this.puzzleQueue = this.getFallbackPuzzles();
      this.startPuzzle(this.puzzleQueue[0]);
    }
  },

  getFallbackPuzzles() {
    // Built-in puzzles for offline/fallback
    return [
      {
        id: 'local_1',
        fen: 'r1bqkb1r/pppp1ppp/2n2n2/4p2Q/2B1P3/8/PPPP1PPP/RNB1K1NR w KQkq - 4 4',
        moves: 'h5f7', // Scholar's mate
        rating: 800,
        themes: ['mate'],
        title: 'مات بنقلة'
      },
      {
        id: 'local_2',
        fen: 'r1b1kb1r/pppp1ppp/5n2/4p1q1/2B1n3/2N2N2/PPPP1PPP/R1BQK2R w KQkq - 0 6',
        moves: 'c3e4 g5g2',
        rating: 1000,
        themes: ['fork'],
        title: 'شوكة'
      },
      {
        id: 'local_3',
        fen: '6k1/5ppp/8/8/8/8/r4PPP/4R1K1 w - - 0 1',
        moves: 'e1e8',
        rating: 900,
        themes: ['endgame'],
        title: 'تبادل قوي'
      }
    ];
  },

  updateDailyProgress() {
    const dots = document.querySelectorAll('.daily-dot');
    dots.forEach((dot, i) => {
      dot.classList.remove('solved', 'current');
      if (i < this.dailySolved) {
        dot.classList.add('solved');
        dot.innerHTML = '<svg class="icon-sm" style="color:var(--text-1)"><use href="/public/icons/sprite.svg#icon-check"></use></svg>';
      } else if (i === this.dailySolved) {
        dot.classList.add('current');
      }
    });
  },

  startPuzzle(puzzle) {
    if (!puzzle) return;

    this.currentPuzzle = puzzle;
    this.isSolving = true;
    this.puzzleStartTime = Date.now();

    // Parse solution moves
    const movesStr = puzzle.moves || '';
    this.puzzleSolution = movesStr.trim().split(/\s+/);
    this.solutionIndex = 0;

    // Setup chess position
    this.chess = new Chess(puzzle.fen);

    // Determine whose turn it is (the player needs to find the move for the side to move)
    const playerSide = this.chess.turn();

    // Show board area
    document.getElementById('puzzle-board-area').style.display = 'block';

    // Init board
    Board.init('board', {
      flipped: playerSide === 'b',
      onMove: (move) => this.handleMove(move)
    });
    Board.setPosition(this.chess);

    // Update puzzle info
    document.getElementById('current-puzzle-rating').textContent = puzzle.rating || '?';
    document.getElementById('puzzle-turn').textContent = playerSide === 'w' ? 'دور الابيض' : 'دور الاسود';

    // Reset status
    const statusEl = document.getElementById('puzzle-status');
    statusEl.textContent = 'جد افضل نقلة';
    statusEl.className = 'puzzle-status';

    // Hide result
    document.getElementById('puzzle-result').style.display = 'none';

    // If puzzle starts with opponent's move first (multi-move puzzle)
    // The first move in the solution is sometimes a "setup" move
    // For simplicity, the solution moves are the player's required moves
  },

  handleMove(move) {
    if (!this.isSolving || !this.currentPuzzle) return;

    const expectedMove = this.puzzleSolution[this.solutionIndex];
    if (!expectedMove) return;

    // Convert player's move to UCI format
    const uciMove = move.from + move.to + (move.promotion || '');

    // Check if the move matches
    if (uciMove === expectedMove || this.isEquivalentMove(move, expectedMove)) {
      // Correct move
      const result = this.chess.move({
        from: move.from,
        to: move.to,
        promotion: move.promotion || 'q'
      });

      if (!result) return;

      Board.lastMove = { from: move.from, to: move.to };
      Board.setPosition(this.chess);
      this.solutionIndex++;

      // Check if puzzle is complete
      if (this.solutionIndex >= this.puzzleSolution.length) {
        this.puzzleSolved(true);
      } else {
        // Show "correct" status briefly, then make opponent's reply
        const statusEl = document.getElementById('puzzle-status');
        statusEl.textContent = 'صحيح! اكمل...';
        statusEl.className = 'puzzle-status correct';

        // Make the next move (opponent's reply) after a delay
        setTimeout(() => {
          this.makeOpponentMove();
        }, 500);
      }
    } else {
      // Wrong move
      this.puzzleSolved(false);
    }
  },

  isEquivalentMove(move, uciExpected) {
    // Check if the move with default queen promotion matches
    const from = uciExpected.substring(0, 2);
    const to = uciExpected.substring(2, 4);
    const promo = uciExpected.length > 4 ? uciExpected[4] : '';

    if (move.from === from && move.to === to) {
      if (!promo) return true;
      if ((move.promotion || 'q') === promo) return true;
    }
    return false;
  },

  makeOpponentMove() {
    const nextMove = this.puzzleSolution[this.solutionIndex];
    if (!nextMove || nextMove.length < 4) return;

    const from = nextMove.substring(0, 2);
    const to = nextMove.substring(2, 4);
    const promotion = nextMove.length > 4 ? nextMove[4] : undefined;

    Board.animateMove(from, to, () => {
      const result = this.chess.move({ from, to, promotion });
      if (result) {
        Board.lastMove = { from, to };
        Board.setPosition(this.chess);
        this.solutionIndex++;

        const statusEl = document.getElementById('puzzle-status');
        statusEl.textContent = 'دورك';
        statusEl.className = 'puzzle-status';
      }
    });
  },

  puzzleSolved(correct) {
    this.isSolving = false;
    const timeMs = Date.now() - this.puzzleStartTime;

    // Update streak
    if (correct) {
      this.currentStreak++;
      if (this.currentStreak > this.bestStreak) {
        this.bestStreak = this.currentStreak;
      }
    } else {
      this.currentStreak = 0;
    }

    // Show result
    const resultEl = document.getElementById('puzzle-result');
    const iconEl = document.getElementById('puzzle-result-icon');
    const textEl = document.getElementById('puzzle-result-text');
    const statusEl = document.getElementById('puzzle-status');

    if (correct) {
      iconEl.innerHTML = '<svg class="icon-lg" style="color:var(--success)"><use href="/public/icons/sprite.svg#icon-check"></use></svg>';
      textEl.textContent = 'احسنت! +' + Math.round(timeMs / 1000) + ' ثانية';
      statusEl.textContent = 'صحيح!';
      statusEl.className = 'puzzle-status correct';
    } else {
      iconEl.innerHTML = '<svg class="icon-lg" style="color:var(--error)"><use href="/public/icons/sprite.svg#icon-x"></use></svg>';
      textEl.textContent = 'خطأ - الحل الصحيح: ' + this.formatSolution();
      statusEl.textContent = 'خطأ';
      statusEl.className = 'puzzle-status wrong';

      // Show correct solution on board
      this.showSolution();
    }

    resultEl.style.display = 'block';
    this.updateStatsUI();

    // Report attempt to server
    this.reportAttempt(correct, timeMs);

    // Handle rush mode
    if (this.isRushActive) {
      if (correct) {
        this.rushCount++;
        document.getElementById('rush-count').textContent = this.rushCount + ' حل';
      } else {
        this.endRush();
      }
    }

    // Handle daily mode
    if (this.mode === 'daily' && correct) {
      this.dailySolved++;
      this.updateDailyProgress();
    }
  },

  formatSolution() {
    return this.puzzleSolution.map(m => {
      if (m.length >= 4) return m.substring(0, 2) + '-' + m.substring(2, 4);
      return m;
    }).join(', ');
  },

  showSolution() {
    // Animate the correct first move
    const correctMove = this.puzzleSolution[this.solutionIndex] || this.puzzleSolution[0];
    if (!correctMove || correctMove.length < 4) return;

    const from = correctMove.substring(0, 2);
    const to = correctMove.substring(2, 4);

    // Highlight the correct squares
    const fromSq = Board.getSquareEl(from);
    const toSq = Board.getSquareEl(to);
    if (fromSq) fromSq.style.background = 'var(--board-highlight-green)';
    if (toSq) toSq.style.background = 'var(--board-highlight-green)';
  },

  async reportAttempt(solved, timeMs) {
    if (!this.currentPuzzle || this.currentPuzzle.id.startsWith('local_')) return;

    try {
      const res = await App.fetch('/api/puzzles', {
        method: 'POST',
        body: JSON.stringify({
          action: 'attempt',
          puzzle_id: this.currentPuzzle.id,
          solved: solved,
          time_ms: timeMs
        })
      });

      if (res && res.rating_after) {
        this.playerRating = res.rating_after;
        this.currentStreak = res.streak;
        this.bestStreak = res.best_streak;
        this.updateStatsUI();

        if (res.coins_awarded > 0) {
          App.toast('+' + res.coins_awarded + ' عملة');
        }
      }
    } catch (e) {}
  },

  nextPuzzle() {
    // Get next puzzle from queue
    const currentIndex = this.puzzleQueue.indexOf(this.currentPuzzle);
    const nextIndex = currentIndex + 1;

    if (nextIndex < this.puzzleQueue.length) {
      this.startPuzzle(this.puzzleQueue[nextIndex]);
    } else if (this.mode === 'streak' || this.isRushActive) {
      // Load more puzzles
      this.loadMorePuzzles();
    } else {
      // Daily complete or theme complete
      document.getElementById('puzzle-board-area').style.display = 'none';
      if (this.mode === 'daily') {
        App.toast('اكملت الالغاز اليومية!', 'success');
      } else {
        App.toast('اكملت جميع الالغاز', 'success');
      }
    }
  },

  async loadMorePuzzles() {
    let url = '/api/puzzles?rating=' + this.playerRating + '&limit=10';
    if (this.selectedTheme) {
      url += '&theme=' + this.selectedTheme;
    }

    try {
      const data = await App.fetch(url);
      if (data && data.puzzles && data.puzzles.length > 0) {
        this.puzzleQueue = data.puzzles;
        this.startPuzzle(this.puzzleQueue[0]);
      } else {
        // Use fallback
        this.puzzleQueue = this.getFallbackPuzzles();
        this.startPuzzle(this.puzzleQueue[0]);
      }
    } catch (e) {
      this.puzzleQueue = this.getFallbackPuzzles();
      this.startPuzzle(this.puzzleQueue[0]);
    }
  },

  // Theme puzzles
  async startThemePuzzles(theme) {
    this.selectedTheme = theme;
    this.mode = 'themes';

    try {
      const data = await App.fetch('/api/puzzles?theme=' + theme + '&rating=' + this.playerRating + '&limit=10');
      if (data && data.puzzles && data.puzzles.length > 0) {
        this.puzzleQueue = data.puzzles;
        this.startPuzzle(this.puzzleQueue[0]);
      } else {
        this.puzzleQueue = this.getFallbackPuzzles();
        this.startPuzzle(this.puzzleQueue[0]);
        App.toast('لا توجد الغاز لهذا الموضوع حاليا');
      }
    } catch (e) {
      this.puzzleQueue = this.getFallbackPuzzles();
      this.startPuzzle(this.puzzleQueue[0]);
    }
  },

  // Streak mode
  async startStreak() {
    this.mode = 'streak';
    this.currentStreak = 0;
    this.updateStatsUI();
    await this.loadMorePuzzles();
  },

  // Rush mode
  async startRush() {
    this.isRushActive = true;
    this.rushTimeLeft = 180;
    this.rushCount = 0;
    this.mode = 'rush';

    document.getElementById('rush-timer').style.display = 'flex';
    document.getElementById('btn-start-rush').style.display = 'none';
    document.getElementById('rush-count').textContent = '0 حل';

    // Start timer
    this.rushTimer = setInterval(() => {
      this.rushTimeLeft--;
      this.updateRushTimer();
      if (this.rushTimeLeft <= 0) {
        this.endRush();
      }
    }, 1000);

    // Load puzzles
    await this.loadMorePuzzles();
  },

  updateRushTimer() {
    const mins = Math.floor(this.rushTimeLeft / 60);
    const secs = this.rushTimeLeft % 60;
    document.getElementById('rush-time').textContent = mins + ':' + secs.toString().padStart(2, '0');
  },

  endRush() {
    this.isRushActive = false;
    if (this.rushTimer) {
      clearInterval(this.rushTimer);
      this.rushTimer = null;
    }

    // Show result
    App.toast('انتهى السباق! حللت ' + this.rushCount + ' لغز', 'success');

    document.getElementById('rush-timer').style.display = 'none';
    document.getElementById('btn-start-rush').style.display = 'inline-flex';
    document.getElementById('puzzle-board-area').style.display = 'none';
    this.isSolving = false;
  }
};
