// src/components/QuizEngineV2.jsx

function QuizEngine({ quizId, onQuizComplete }) {
  // 🚀 FIX: Leggiamo la lingua direttamente dalla configurazione globale, non dall'utente!
  const lang = typeof APP_CONFIG !== 'undefined' && APP_CONFIG.enableItalian ? 'it' : 'en';
  
  const [questions, setQuestions] = React.useState(null); 
  const [profiles, setProfiles] = React.useState([]); 
  const [currentId, setCurrentId] = React.useState('start'); 
  const [currentIndex, setCurrentIndex] = React.useState(0); 
  const [score, setScore] = React.useState(0);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [userAnswers, setUserAnswers] = React.useState([]);

  const shuffleArray = (array) => {
    const shuffled = [...array];
    for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }
    return shuffled;
  };

  React.useEffect(() => {
    const loadQuizData = async () => {
      try {
        const response = await fetch("/domande.json");
        if (!response.ok) throw new Error("File domande.json non trovato.");
        const data = await response.json();
        setProfiles(data.profiles || []);

        const rawQuestions = data.questions && data.questions[quizId] ? data.questions[quizId] : [];
        const validRows = [];
        let questionCounter = 1;

        rawQuestions.forEach((row) => {
          let cleanedId = row.id !== undefined && row.id !== null ? String(row.id).trim() : "";
          if (cleanedId === "" || cleanedId === "null" || cleanedId === "undefined") {
            cleanedId = String(questionCounter);
          }
          const testoIT = row.testo_it || row.testoit || "";
          const testoEN = row.testo_en || row.testoen || "";
          const testoFinale = lang === 'en' ? (testoEN || testoIT) : (testoIT || testoEN);

          if (testoFinale.length > 0) {
            validRows.push({ ...row, id: cleanedId, testo_visualizzato: testoFinale });
            questionCounter++;
          }
        });

        if (quizId === 'q1') {
          setQuestions(shuffleArray(validRows).slice(0, Math.min(validRows.length, 10)));
        } else {
          const treeMap = {};
          validRows.forEach(item => { treeMap[String(item.id).toLowerCase().trim()] = item; });
          const firstId = validRows[0] && validRows[0].id ? String(validRows[0].id).toLowerCase().trim() : 'start';
          setCurrentId(treeMap['start'] ? 'start' : firstId);
          setQuestions(treeMap);
        }
        setLoading(false);
      } catch (err) {
        console.error(err);
        setError("Errore nel caricamento del modulo quiz.");
        setLoading(false);
      }
    };
    loadQuizData();
  }, [quizId, lang]);

  const currentQuestion = React.useMemo(() => {
    if (!questions) return null;
    return quizId === 'q1' ? (questions[currentIndex] || null) : (questions[currentId ? String(currentId).toLowerCase().trim() : ''] || null);
  }, [questions, currentIndex, currentId, quizId]);

  const shuffledAnswers = React.useMemo(() => {
    if (!currentQuestion) return [];
    const rawAnswers = [];
    for (let num = 1; num <= 10; num++) {
      const testoRisposta = currentQuestion[`opzione_${num}_${lang}`] || currentQuestion[`opzione${num}${lang}`];
      if (testoRisposta && String(testoRisposta).trim().length > 0) {
        rawAnswers.push({
          testo: String(testoRisposta).trim(),
          go_to: String(currentQuestion[`go_to_${num}`] || currentQuestion[`goto${num}`] || "").trim(),
          punti: String(currentQuestion[`punti_${num}`] || currentQuestion[`punti${num}`] || "0").trim()
        });
      }
    }
    return shuffleArray(rawAnswers);
  }, [currentQuestion, lang]);

  const getProfileForScore = React.useCallback((targetScore) => {
    const currentNumericScore = Number(targetScore) || 0;
    const cleanCurrentId = String(quizId).toLowerCase().trim();

    if (!profiles || !profiles.length) return { titolo: "Completato", descrizione: "" };

    const matched = profiles.find(p => {
      const jsonQuizId = String(p.quiz_id).toLowerCase().trim();
      const isExactMatch = jsonQuizId === cleanCurrentId;
      const min = Number(p.min_score) || 0;
      const max = Number(p.max_score) || 0;
      return isExactMatch && currentNumericScore >= min && currentNumericScore <= max;
    });

    return matched ? {
      titolo: lang === 'en' ? matched.titolo_en : matched.titolo_it,
      descrizione: lang === 'en' ? matched.descrizione_en : matched.descrizione_it
    } : { titolo: "Completato", descrizione: "" };
  }, [profiles, quizId, lang]);

  const handleAnswerClick = (goTo, points, testoRisposta) => {
    if (document.activeElement && typeof document.activeElement.blur === 'function') {
      document.activeElement.blur();
    }

    if (!currentQuestion) return;
    const nuovaCoppia = { domanda: currentQuestion.testo_visualizzato || "Domanda", risposta_scelta: testoRisposta };
    const updatedAnswers = [...userAnswers, nuovaCoppia];
    setUserAnswers(updatedAnswers);
    
    const nextScore = score + (parseInt(points, 10) || 0);
    setScore(nextScore);

    // Quando le domande finiscono, passa i dati al Form di Registrazione
    if (quizId === 'q1') {
      if (currentIndex + 1 >= questions.length) {
        onQuizComplete(nextScore, getProfileForScore(nextScore), updatedAnswers);
      } else { setCurrentIndex(currentIndex + 1); }
    } else {
      const nextNode = goTo ? goTo.trim().toLowerCase() : 'fine';
      if (nextNode === 'fine' || nextNode === '' || !questions[nextNode]) {
        onQuizComplete(nextScore, getProfileForScore(nextScore), updatedAnswers);
      } else { setCurrentId(nextNode); }
    }
  };

  if (loading) return <div className="min-h-screen flex items-center justify-center bg-slate-50"><div className="animate-spin w-8 h-8 border-4 border-indigo-600 border-t-transparent rounded-full"></div></div>;
  if (error) return <div className="min-h-screen flex items-center justify-center bg-slate-50 p-4"><div className="text-red-600 font-bold bg-white p-6 rounded-2xl border border-slate-200 shadow-md">{error}</div></div>;

  return (
    <div className="min-h-screen flex items-center justify-center bg-slate-50 px-4 py-12 text-slate-900">
      <div className="max-w-2xl w-full bg-white border border-slate-200 p-8 rounded-3xl shadow-xl animate-fadeIn">
        <div className="mb-6 flex justify-between items-center border-b border-slate-100 pb-4">
          <span className="text-xs font-black text-indigo-600 uppercase tracking-widest bg-indigo-50 px-3 py-1.5 rounded-full border border-indigo-100 shadow-sm">
            {lang === 'en' ? `Question ${userAnswers.length + 1}` : `Domanda ${userAnswers.length + 1}`}
          </span>
        </div>
        <div className="mb-8">
          <h2 className="text-2xl font-black text-slate-900 tracking-tight leading-snug">{currentQuestion?.testo_visualizzato}</h2>
        </div>
        <div className="space-y-4">
          {shuffledAnswers.map((ans, idx) => {
            const uniqueKey = `${currentQuestion?.id || currentIndex}_ans_${idx}`;
            return (
              <button 
                key={uniqueKey} 
                onClick={() => handleAnswerClick(ans.go_to, ans.punti, ans.testo)} 
                className="w-full text-left p-5 bg-slate-50 active:bg-indigo-600 border border-slate-200 text-slate-800 active:text-white md:hover:bg-indigo-600 md:hover:text-white md:hover:border-transparent font-semibold rounded-2xl shadow-sm md:hover:shadow-md transition-all duration-150 cursor-pointer text-sm leading-relaxed touch-manipulation"
              >
                {ans.testo}
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.QuizEngineV2 = QuizEngine;