// src/App.jsx

// 1. RECUPERO ESPLICITO DEI COMPONENTI DALLA MEMORIA GLOBALE
const DashboardView = window.Dashboard;
const QuizEngineView = window.QuizEngineV2;
const AuthFlowView = window.AuthFlow;

function App() {
  const [appStep, setAppStep] = React.useState('dashboard');
  const [selectedQuizId, setSelectedQuizId] = React.useState(null);
  const [userRole, setUserRole] = React.useState(""); 
  const [quizResult, setQuizResult] = React.useState(null);
  const [userData, setUserData] = React.useState(null);
  
  // 2. LETTURA SICURA DELLA CONFIGURAZIONE
  const isItalian = typeof window.APP_CONFIG !== 'undefined' ? window.APP_CONFIG.enableItalian : false;
  const lang = isItalian ? 'it' : 'en';
  
  const QUIZ_TITLES = { q1: "Harmonised compliance", q2: "OT Resilience & Integrity", q3: "ESG & CSR", q4: "Digital Validation", q5: "Artificial Intelligence" };

  const urlParams = new URLSearchParams(window.location.search);
  const isCollegaView = urlParams.get('view') === 'lead';

  if (isCollegaView) {
    return DashboardView ? <DashboardView /> : <div>Caricamento Dashboard Live...</div>;
  }

  const handleQuizComplete = (score, profile, answers) => {
    setQuizResult({ score, profile, answers });
    setAppStep('auth');
  };

  const handleAuthComplete = async (data) => {
    setUserData(data);
    setAppStep('certificate');
    
    try {
      if (!window.firebase || !window.firebase.firestore) return;
      const db = window.firebase.firestore();
      
      const safeName = (data.name || "Anonimo").trim().replace(/\s+/g, '_');
      const safeSurname = (data.surname || "Lead").trim().replace(/\s+/g, '_');
      const customDocId = `${safeSurname}_${safeName}_${Date.now()}`;

      const payloadFiera = {
        createdAt: new Date(), 
        name: data.name || "",
        surname: data.surname || "",
        company: data.company || "",
        role: userRole || "", 
        email: data.email || "",
        phone: data.phone || "",
        language: data.language || lang,
        quizId: selectedQuizId,
        quizTitle: QUIZ_TITLES[selectedQuizId] || "",
        score: Number(quizResult.score),
        profileTitle: quizResult.profile.titolo || "",
        profileDesc: quizResult.profile.descrizione || "",
        answers: quizResult.answers
      };

      const maxScores = { q1: 100, q2: 44, q3: 48, q4: 84, q5: 52 };
      const maxScore = maxScores[selectedQuizId] || 100;

      await db.collection("lead_fiera_2026").doc(customDocId).set(payloadFiera);
      
      await db.collection("mail").add({
        to: data.email,
        message: {
          subject: data.language === 'en' ? `MAASI ENTERPRISES: Your Assessment Certificate - ${QUIZ_TITLES[selectedQuizId]}` : `MAASI ENTERPRISES: Il tuo Attestato Assessment - ${QUIZ_TITLES[selectedQuizId]}`,
          html: `
            <div style="font-family: sans-serif; color: #333; max-width: 600px; margin: 0 auto; padding: 30px; border: 1px solid #e2e8f0; border-radius: 16px; background-color: #ffffff;">
              <div style="text-align: center; margin-bottom: 25px; border-bottom: 1px solid #e2e8f0; padding-bottom: 15px;">
                <span style="font-size: 14px; font-weight: bold; letter-spacing: 1px; color: #1e3a8a; font-family: monospace;">MAASI ENTERPRISES</span>
                <h2 style="color: #4f46e5; margin: 10px 0 0 0; font-size: 22px;">${data.language === 'en' ? "Assessment Completed!" : "Assessment Completato!"}</h2>
              </div>
              <p style="font-size: 15px; line-height: 1.5;">${data.language === 'en' ? `Dear <b>${data.name} ${data.surname}</b>,` : `Gentile <b>${data.name} ${data.surname}</b>,`}</p>
              <p style="font-size: 15px; line-height: 1.5;">${data.language === 'en' ? "Thank you for completing the assessment. Here is the summary of your specialized profile:" : "Grazie per aver completato il tuo assessment. Di seguito trovi il riepilogo del tuo profilo specialistico:"}</p>
              <div style="background-color: #f8fafc; padding: 20px; border-left: 4px solid #4f46e5; border-radius: 4px; margin: 25px 0;">
                <table style="width: 100%; font-size: 14px; border-collapse: collapse;">
                  <tr><td style="padding: 6px 0; color: #64748b;"><b>Assessment:</b></td><td style="padding: 6px 0; color: #1e293b; font-weight: bold;">${QUIZ_TITLES[selectedQuizId]}</td></tr>
                  <tr><td style="padding: 6px 0; color: #64748b;"><b>${data.language === 'en' ? "Result Profile:" : "Profilo Risultato:"}</b></td><td style="padding: 6px 0; color: #4f46e5; font-weight: bold;">${quizResult.profile.titolo}</td></tr>
                  <tr><td style="padding: 6px 0; color: #64748b;"><b>${data.language === 'en' ? "Total Score:" : "Punteggio Totale:"}</b></td><td style="padding: 6px 0; color: #0f172a; font-weight: bold;">${quizResult.score} / ${maxScore} pt</td></tr>
                </table>
              </div>
              <p style="font-size: 14px; color: #475569; line-height: 1.5; font-style: italic; background: #f0f4ff; padding: 15px; border-radius: 8px; border-left: 4px solid #3b82f6;">${quizResult.profile.descrizione || ""}</p>
              <hr style="border: none; border-top: 1px solid #e2e8f0; margin: 30px 0;" />
              <p style="font-size: 11px; color: #94a3b8; text-align: center; margin: 0;">MAASI ENTERPRISES</p>
            </div>
          `
        }
      });
    } catch (err) {
      console.error("Errore salvataggio:", err);
    }
  };

  const restartApp = () => {
    setAppStep('dashboard');
    setSelectedQuizId(null);
    setUserRole("");
    setQuizResult(null);
    setUserData(null);
  };

  return (
    <div>
      {appStep === 'dashboard' && DashboardView && (
        <DashboardView onSelectQuiz={(id) => { setSelectedQuizId(id); setAppStep('role_select'); }} />
      )}

      {appStep === 'role_select' && (
        <RoleSelectionView 
          lang={lang} 
          onBack={() => setAppStep('dashboard')}
          onComplete={(role) => { setUserRole(role); setAppStep('quiz_run'); }} 
        />
      )}
      
      {appStep === 'quiz_run' && QuizEngineView && (
        <QuizEngineView quizId={selectedQuizId} onQuizComplete={handleQuizComplete} />
      )}

      {appStep === 'auth' && AuthFlowView && (
        <AuthFlowView onComplete={handleAuthComplete} />
      )}
      
      {appStep === 'certificate' && userData && quizResult && (
        <CertificateView 
          user={{...userData, role: userRole}} 
          quizId={selectedQuizId} 
          quizTitle={QUIZ_TITLES[selectedQuizId]} 
          score={quizResult.score} 
          profile={quizResult.profile} 
          onRestart={restartApp} 
        />
      )}
    </div>
  );
}

// COMPONENTE PER LA SCELTA DEL RUOLO
function RoleSelectionView({ lang, onBack, onComplete }) {
  const [role, setRole] = React.useState("");
  const [customRole, setCustomRole] = React.useState("");
  
  const roles = typeof window.pharmaRoles !== 'undefined' ? window.pharmaRoles : [
    "Medical Affairs", "R&D", "Sales & Key Account", "Marketing", "Regulatory Affairs", "Market Access", "Pharmacovigilance", "Altro"
  ];

  const handleContinue = () => {
    if (!role) return;
    const finalRole = role === "Altro" ? customRole.trim() : role;
    if (role === "Altro" && !finalRole) return; 
    onComplete(finalRole);
  };

  return (
    <div className="min-h-screen flex flex-col items-center justify-center bg-slate-50 px-4 py-12 text-slate-900">
      <div className="max-w-md w-full bg-white border border-slate-200 p-8 rounded-3xl shadow-xl animate-fadeIn">
        <div className="mb-8 text-center">
          <h2 className="text-3xl font-black text-slate-900 tracking-tight">{lang === 'en' ? "Select your Role" : "Seleziona il tuo Ruolo"}</h2>
          <p className="text-sm text-slate-500 mt-2">{lang === 'en' ? "Choose your profile to customize the assessment." : "Scegli il tuo profilo aziendale per iniziare."}</p>
        </div>

        <div className="space-y-5">
          <div className="relative">
            <select
              value={role}
              onChange={(e) => { setRole(e.target.value); if (e.target.value !== "Altro") setCustomRole(""); }}
              className="w-full px-4 py-4 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-indigo-500 focus:bg-white transition-all font-medium appearance-none cursor-pointer"
            >
              <option value="" disabled>{lang === 'en' ? "Select your role..." : "Seleziona il tuo ruolo..."}</option>
              {roles.map((r, idx) => {
                const label = r === "Altro" && lang === "en" ? "Other" : r;
                return <option key={idx} value={r}>{label}</option>;
              })}
            </select>
            <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-4 text-slate-500">▼</div>
          </div>

          {role === "Altro" && (
            <div className="animate-fadeIn">
              <input type="text" placeholder={lang === 'en' ? "Specify your role" : "Specifica il tuo ruolo"} value={customRole} onChange={(e) => setCustomRole(e.target.value)} className="w-full px-4 py-3 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 focus:outline-none focus:border-indigo-500 focus:bg-white transition-all text-sm" />
            </div>
          )}

          <button onClick={handleContinue} disabled={!role || (role === 'Altro' && !customRole.trim())} className={`w-full font-bold py-4 px-6 rounded-xl transition-all duration-300 ${(!role || (role === 'Altro' && !customRole.trim())) ? 'bg-slate-100 text-slate-400 cursor-not-allowed opacity-70' : 'bg-indigo-600 text-white shadow-md hover:bg-indigo-700 cursor-pointer'}`}>
            {lang === 'en' ? "Start Assessment" : "Inizia Assessment"}
          </button>
          
          <button onClick={onBack} className="w-full text-center text-xs text-slate-400 hover:text-indigo-600 mt-4 font-semibold transition-colors cursor-pointer">
             {lang === 'en' ? "← Back to Quizzes" : "← Torna ai Quiz"}
          </button>
        </div>
      </div>
    </div>
  );
}

// COMPONENTE CERTIFICATO FINALE
function CertificateView({ user, quizId, quizTitle, score, profile, onRestart }) {
  const lang = user.language || 'en';
  const leadMock = { name: user.name, surname: user.surname, role: user.role, company: user.company, quizId: quizId, quizTitle: quizTitle, score: score, profileTitle: profile.titolo, profileDesc: profile.descrizione, language: lang };
  const certificatoHtml = window.generaHtmlCertificato ? window.generaHtmlCertificato(leadMock) : "";

  React.useEffect(() => {
    let autoResetTimer = setTimeout(onRestart, 90000);
    const riazzeraIlConteggio = () => { clearTimeout(autoResetTimer); autoResetTimer = setTimeout(onRestart, 90000); };
    window.addEventListener('click', riazzeraIlConteggio); window.addEventListener('touchstart', riazzeraIlConteggio);
    return () => { clearTimeout(autoResetTimer); window.removeEventListener('click', riazzeraIlConteggio); window.removeEventListener('touchstart', riazzeraIlConteggio); };
  }, [onRestart]);

  return (
    <div className="min-h-screen bg-slate-50 flex flex-col justify-between p-4 box-border">
      <div className="w-full max-w-2xl mx-auto bg-indigo-50 border border-indigo-100 p-3 rounded-xl text-center shadow-sm animate-fadeIn shrink-0 mt-4">
        <p className="text-xs sm:text-sm font-semibold text-indigo-900 flex items-center justify-center gap-2 m-0"><span>📬</span>{lang === 'en' ? "An email containing your technical assessment summary has been sent." : "Un'email con il riepilogo del tuo assessment tecnico è stata inviata."}</p>
      </div>
      <div className="flex-1 w-full max-w-4xl mx-auto flex items-center justify-center min-h-[350px] max-h-[70vh] my-4">
        <iframe srcDoc={certificatoHtml} title="Certificato" className="w-full h-full border-0 rounded-2xl shadow-xl bg-white" style={{ aspectRatio: '297/210' }} />
      </div>
      <div className="w-full max-w-2xl mx-auto text-center pb-4 shrink-0">
        <button onClick={onRestart} className="w-full max-w-xs px-8 py-3.5 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-xl shadow-lg transition-all transform hover:-translate-y-0.5 cursor-pointer text-base tracking-wide">{lang === 'en' ? "Finish and Restart" : "Termina e Riavvia"}</button>
      </div>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);