import { useRef } from 'react';
import ConceptExplainer from './ConceptExplainer';
import ScenarioQuiz from './ScenarioQuiz';
import FlashcardSet from './FlashcardSet';
import { useMicroLearningCompletions } from '../../hooks/useMicroLearningCompletions';

export default function MicroLearningContainer({ microLearning, sessionWeek, onCompletedSuccessfully }) {
  const { recordCompletion } = useMicroLearningCompletions();
  // Ref-guard against double-fire while the await is in flight — using state
  // would let a second click slip through before the re-render lands.
  const recordingRef = useRef(false);

  const handleComplete = async () => {
    if (recordingRef.current) return;
    recordingRef.current = true;

    const record = await recordCompletion({
      microLearningId: microLearning.id,
      topicId: microLearning.topic_id,
      type: microLearning.type,
      sessionWeek: sessionWeek,
    });

    if (record && onCompletedSuccessfully) {
      onCompletedSuccessfully(record);
    } else if (!record) {
      // Allow a retry if persistence failed.
      recordingRef.current = false;
    }
  };

  const renderComponent = () => {
    const props = {
      content: microLearning.content,
      onComplete: handleComplete,
    };

    switch (microLearning.type) {
      case 'concept_explainer':
        return <ConceptExplainer {...props} />;
      case 'scenario_quiz':
        return <ScenarioQuiz {...props} />;
      case 'flashcard_set':
        return <FlashcardSet {...props} />;
      default:
        return <div>Unknown micro learning type.</div>;
    }
  };

  return <div className="w-full max-w-3xl mx-auto">{renderComponent()}</div>;
}
