import { useEffect, useRef } from 'react';
import { getAnalytics } from './AnalyticsManager';

/**
 * Hook para rastrear atividades de jogos com estado (GameStateContext)
 * Rastreia: acesso, fases, sucesso/falha, seleção, tempo
 */
export function useGameActivityTracking(gameConfig, gameState) {
  const analyticsRef = useRef(getAnalytics());
  const sessionStartRef = useRef(Date.now());
  const phaseStartRef = useRef(Date.now());
  const trackedEventsRef = useRef(new Set());
  const firstSuccessTrackedRef = useRef(false);

  const getCommonEventData = () => ({
    editor_tipo: gameState?.editorType || 'blockly',
    blocos_atuais: gameState?.currentBlockCount || 0,
  });

  // Track activity start
  useEffect(() => {
    if (!gameConfig?.gameId) return;

    sessionStartRef.current = Date.now();

    analyticsRef.current.trackEvent('atividade_acessada', {
      atividade_id: gameConfig.gameId,
      atividade_nome: gameConfig.gameName || gameConfig.gameId,
      categoria: gameConfig.categoria || 'programacao',
      dificuldade: gameConfig.dificuldade || 'desconhecida',
      total_fases: gameConfig.fases?.length || 0,
      ...getCommonEventData(),
    });
  }, [gameConfig?.gameId]);

  // Track phase change
  useEffect(() => {
    if (!gameConfig?.gameId || !gameState?.currentPhase) return;

    phaseStartRef.current = Date.now();
    const phase = gameConfig.fases[gameState.currentPhase - 1];

    analyticsRef.current.trackEvent('fase_selecionada', {
      atividade_id: gameConfig.gameId,
      fase_numero: gameState.currentPhase,
      fase_nome: phase?.nome || `Fase ${gameState.currentPhase}`,
      ...getCommonEventData(),
    });
  }, [gameState?.currentPhase, gameConfig?.gameId]);

  // Track phase success/failure
  useEffect(() => {
    if (!gameConfig?.gameId || !gameState) return;

    const { executionState, currentPhase } = gameState;
    const phase = gameConfig.fases[currentPhase - 1];

    // Success
    if (executionState === 'sucesso') {
      const eventKey = `success-${currentPhase}`;
      if (!trackedEventsRef.current.has(eventKey)) {
        trackedEventsRef.current.add(eventKey);

        const phaseTime = Math.round((Date.now() - phaseStartRef.current) / 1000);
        const sessionTime = Math.round((Date.now() - sessionStartRef.current) / 1000);

        analyticsRef.current.trackEvent('fase_completada', {
          atividade_id: gameConfig.gameId,
          atividade_nome: gameConfig.gameName || gameConfig.gameId,
          fase_numero: currentPhase,
          fase_nome: phase?.nome || `Fase ${currentPhase}`,
          tempo_fase_segundos: phaseTime,
          tempo_sessao_segundos: sessionTime,
          categoria: gameConfig.categoria || 'programacao',
          ...getCommonEventData(),
        });

        if (!firstSuccessTrackedRef.current) {
          firstSuccessTrackedRef.current = true;
          analyticsRef.current.trackEvent('tempo_ate_primeiro_sucesso', {
            atividade_id: gameConfig.gameId,
            atividade_nome: gameConfig.gameName || gameConfig.gameId,
            fase_numero: currentPhase,
            tempo_sessao_segundos: sessionTime,
            categoria: gameConfig.categoria || 'programacao',
            ...getCommonEventData(),
          });
        }
      }
    }

    // Failure
    if (executionState === 'falha') {
      const eventKey = `failure-${currentPhase}`;
      if (!trackedEventsRef.current.has(eventKey)) {
        trackedEventsRef.current.add(eventKey);

        const phaseTime = Math.round((Date.now() - phaseStartRef.current) / 1000);

        analyticsRef.current.trackEvent('fase_falhou', {
          atividade_id: gameConfig.gameId,
          fase_numero: currentPhase,
          fase_nome: phase?.nome || `Fase ${currentPhase}`,
          tempo_fase_segundos: phaseTime,
          ...getCommonEventData(),
        });
      }
    }
  }, [gameState?.executionState, gameState?.currentPhase, gameConfig?.gameId]);

  // Track activity abandonment on unmount
  useEffect(() => {
    return () => {
      if (gameConfig?.gameId) {
        const sessionTime = Math.round((Date.now() - sessionStartRef.current) / 1000);

        analyticsRef.current.trackEvent('atividade_abandonada', {
          atividade_id: gameConfig.gameId,
          atividade_nome: gameConfig.gameName || gameConfig.gameId,
          tempo_sessao_segundos: sessionTime,
          ...getCommonEventData(),
        });
      }
    };
  }, [gameConfig?.gameId]);
}
