import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { cursosData } from '../data/quizzes';

export default function QuizPage() {
  const navigate = useNavigate();
  const [currentQ, setCurrentQ] = useState(0);
  const [score, setScore] = useState(0);
  const [questions, setQuestions] = useState([]);
  const [cursoName, setCursoName] = useState('');

  useEffect(() => {
    const lead = JSON.parse(localStorage.getItem('currentLead') || '{}');
    const cursoId = lead.curso || 'generico';
    
    // Load specific questions for the selected course, or fallback to generic
    const data = cursosData[cursoId] || cursosData['generico'];
    setQuestions(data.perguntas);
    setCursoName(data.nome);
  }, []);

  const handleAnswer = (index) => {
    let newScore = score;
    if (index === questions[currentQ].correta) {
      newScore += 20; // 5 questions = 100 points
      setScore(newScore);
    }

    if (currentQ < questions.length - 1) {
      setCurrentQ(currentQ + 1);
    } else {
      const lead = JSON.parse(localStorage.getItem('currentLead') || '{}');
      lead.pontuacao = newScore;
      localStorage.setItem('currentLead', JSON.stringify(lead));
      
      // Save to leads array (simulate DB)
      const allLeads = JSON.parse(localStorage.getItem('leads_db') || '[]');
      allLeads.push({...lead, timestamp: new Date().toISOString()});
      localStorage.setItem('leads_db', JSON.stringify(allLeads));

      navigate('/resultado');
    }
  };

  if (questions.length === 0) return <div className="text-center mt-10">Carregando Campo...</div>;

  const progress = ((currentQ) / questions.length) * 100;

  return (
    <div className="glass-panel animate-fade-in delay-200">
      <div className="text-center mb-4 text-sm text-muted">
        Jogando por: <strong style={{color: 'var(--text-main)'}}>{cursoName}</strong>
      </div>
      
      <div className="flex justify-between items-center mb-2">
        <span className="text-sm font-bold text-muted">Pergunta {currentQ + 1} de {questions.length}</span>
        <span className="text-sm font-bold" style={{color: 'var(--secondary-color)'}}>Valendo 20 pts</span>
      </div>
      
      <div className="progress-bar-bg">
        <div className="progress-bar-fill" style={{ width: `${progress}%` }}></div>
      </div>

      <h3 className="text-xl font-bold mb-8 mt-6">
        {questions[currentQ].pergunta}
      </h3>

      <div className="flex flex-col gap-4">
        {questions[currentQ].opcoes.map((opt, idx) => (
          <button 
            key={idx} 
            className="quiz-option"
            onClick={() => handleAnswer(idx)}
          >
            <div 
              translate="no" 
              className="notranslate"
              style={{ 
                width: '32px', height: '32px', borderRadius: '50%', 
                display: 'flex', alignItems: 'center', justifyContent: 'center', 
                fontWeight: 'bold', fontSize: '14px', 
                background: 'rgba(255,255,255,0.1)', flexShrink: 0 
              }}
            >
              {String.fromCharCode(65 + idx)}
            </div>
            <span style={{textAlign: 'left'}}>{opt}</span>
          </button>
        ))}
      </div>
    </div>
  );
}
