const { useEffect, useMemo, useState } = React;

const unique = (items) => Array.from(new Set(items));

const pickMeaning = (word, language) =>
  language === "Nepali" ? word.nepali : word.english;

const buildOptions = (correct, wrongPool) => {
  const options = [correct];
  const shuffledWrong = window.shuffle(wrongPool);
  for (let i = 0; i < shuffledWrong.length && options.length < 4; i += 1) {
    if (!options.includes(shuffledWrong[i])) {
      options.push(shuffledWrong[i]);
    }
  }
  return window.shuffle(options);
};

const buildMcqQuestions = (words, count, quizId) => {
  const questions = [];
  const pool = window.shuffle(words);
  let index = 0;

  while (questions.length < count && index < count * 4) {
    const word = pool[index % pool.length];
    const language = questions.length % 2 === 0 ? "English" : "Nepali";
    const correct = pickMeaning(word, language);

    const wrongPool = unique(
      words
        .filter((item) => item.newari !== word.newari)
        .map((item) => pickMeaning(item, language))
    ).filter(Boolean);

    if (!correct || wrongPool.length < 3) {
      index += 1;
      continue;
    }

    const options = buildOptions(correct, wrongPool);

    questions.push({
      id: `mcq-${word.newari}-${language}-${questions.length}-${quizId}`,
      type: "mcq",
      prompt: `What does "${word.newari}" mean in ${language}?`,
      options,
      answer: correct
    });

    index += 1;
  }

  return questions;
};

const buildMatchQuestions = (words, quizId) => {
  const pairsPerMatch = Math.min(5, words.length);
  const matchCount = words.length >= 8 ? 2 : 1;

  return Array.from({ length: matchCount }).map((_, index) => {
    const pairs = window.shuffle(words)
      .slice(0, pairsPerMatch)
      .map((word) => ({
        left: word.newari,
        right: `${word.english} / ${word.nepali}`
      }));

    return {
      id: `match-${index}-${quizId}`,
      type: "match",
      prompt: "Match the Newari words to their meanings.",
      pairs
    };
  });
};

const buildQuestions = (lesson, quizId) => {
  if (lesson.type === "sentence_building") {
    return window.shuffle(lesson.questions).map((question, index) => ({
      ...question,
      id: question.id || `sentence-${index}-${quizId}`,
      type: "sentence"
    }));
  }

  const minCount = lesson.questionCountMin ?? 10;
  const maxCount = lesson.questionCountMax ?? 15;
  const baseMcqCount = Math.min(Math.max(lesson.words.length, 8), 12);

  let mcqs = buildMcqQuestions(lesson.words, baseMcqCount, quizId);
  const matches = buildMatchQuestions(lesson.words, quizId);
  let combined = window.shuffle([...mcqs, ...matches]);

  if (combined.length < minCount) {
    mcqs = buildMcqQuestions(lesson.words, minCount - combined.length + 2, quizId);
    combined = window.shuffle([...combined, ...mcqs]);
  }

  const maxAvailable = Math.min(maxCount, combined.length);
  const targetSize = Math.min(
    maxAvailable,
    Math.max(minCount, Math.floor(Math.random() * (maxCount - minCount + 1)) + minCount)
  );
  return combined.slice(0, targetSize);
};

window.buildQuestions = buildQuestions;

const QuizEngine = ({ lesson, questions, onExit, onReview }) => {
  const [index, setIndex] = useState(0);
  const [score, setScore] = useState(0);
  const [locked, setLocked] = useState(false);

  useEffect(() => {
    setIndex(0);
    setScore(0);
    setLocked(false);
  }, [lesson.id, questions]);

  const current = questions[index];
  const total = questions.length;

  if (!questions.length) {
    return (
      <div className="card">
        <p className="lesson-meta">No questions available yet.</p>
        <button className="btn" onClick={onExit}>
          Back to lessons
        </button>
      </div>
    );
  }

  const handleAnswer = (correct) => {
    if (locked) return;
    setLocked(true);
    if (correct) setScore((prev) => prev + 1);
  };

  const handleNext = () => {
    setLocked(false);
    setIndex((prev) => prev + 1);
  };

  if (index >= total) {
    const percent = Math.round((score / total) * 100);
    const passed = percent >= 80;
    return (
      <div className="card">
        <h2>Quiz results</h2>
        <p className="score">Final score: {score} / {total}</p>
        <p className={`result ${passed ? "result-pass" : "result-fail"}`}>
          {passed ? "Pass" : "Try again"} ({percent}%)
        </p>
        <div className="footer-actions">
          <button className="btn-secondary btn" onClick={onReview}>
            Review words
          </button>
          <button className="btn" onClick={onExit}>
            Back to lessons
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="card">
      <div className="quiz-header">
        <div className="progress">
          Question {index + 1} of {total}
        </div>
        <div className="badge">Score: {score}</div>
      </div>
      {current.type === "mcq" ? (
        <MCQQuestion key={current.id} question={current} onAnswer={handleAnswer} />
      ) : current.type === "match" ? (
        <MatchQuestion key={current.id} question={current} onAnswer={handleAnswer} />
      ) : (
        <SentenceBuilder key={current.id} question={current} onAnswer={handleAnswer} />
      )}
      <div className="footer-actions">
        <button className="btn-secondary btn" onClick={onExit}>
          Exit lesson
        </button>
        <button className="btn" onClick={handleNext} disabled={!locked}>
          Next
        </button>
      </div>
    </div>
  );
};
