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

export function useActivityTracking(gameConfig) {
  const analyticsRef = useRef(getAnalytics());
  const sessionStartRef = useRef(Date.now());
  const trackedEventsRef = useRef(new Set());

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

    sessionStartRef.current = Date.now();
    analyticsRef.current.trackEvent('atividade_iniciada', {
      atividade_id: gameConfig.gameId,
      atividade_nome: gameConfig.gameName || gameConfig.gameId,
      categoria: gameConfig.categoria || 'programacao',
      dificuldade: gameConfig.dificuldade || 'desconhecida',
      total_fases: gameConfig.fases?.length || 0,
      conceitos: gameConfig.conceitos?.join(',') || '',
    });
  }, [gameConfig?.gameId, gameConfig?.gameName, gameConfig?.categoria, gameConfig?.dificuldade, gameConfig?.fases?.length, gameConfig?.conceitos]);

  // Track phase completion
  const trackPhaseCompletion = (phaseId, phaseName, success) => {
    if (!gameConfig?.gameId) return;

    const eventKey = `phase-${phaseId}-${success}`;
    if (trackedEventsRef.current.has(eventKey)) return;
    trackedEventsRef.current.add(eventKey);

    const sessionDuration = Math.round((Date.now() - sessionStartRef.current) / 1000);

    analyticsRef.current.trackEvent(
      success ? 'fase_completada' : 'fase_falhou',
      {
        atividade_id: gameConfig.gameId,
        atividade_nome: gameConfig.gameName || gameConfig.gameId,
        fase_numero: phaseId,
        fase_nome: phaseName || `Fase ${phaseId}`,
        tempo_sessao_segundos: sessionDuration,
        categoria: gameConfig.categoria || 'programacao',
      }
    );
  };

  // Track activity abandonment
  const trackActivityAbandonment = () => {
    if (!gameConfig?.gameId) return;

    analyticsRef.current.trackEvent('atividade_abandonada', {
      atividade_id: gameConfig.gameId,
      atividade_nome: gameConfig.gameName || gameConfig.gameId,
      tempo_sessao_segundos: Math.round((Date.now() - sessionStartRef.current) / 1000),
    });
  };

  // Track custom activity event
  const trackActivityEvent = (eventName, eventData = {}) => {
    if (!gameConfig?.gameId) return;

    analyticsRef.current.trackEvent(eventName, {
      atividade_id: gameConfig.gameId,
      atividade_nome: gameConfig.gameName || gameConfig.gameId,
      ...eventData,
    });
  };

  return {
    trackPhaseCompletion,
    trackActivityAbandonment,
    trackActivityEvent,
  };
}
