// src/App.jsx

// 1. COMPONENTE MODALE PER LA SCELTA DEL RUOLO
function RoleSelectionModal({ lang, onSelectRole, onBack }) {
  const t = translations[lang] || translations.it;

  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-md w-full bg-white border border-slate-200 p-8 rounded-3xl shadow-xl animate-fadeIn">
        <h2 className="text-2xl font-black text-slate-900 tracking-tight mb-2">
          {t.selectRoleTitle}
        </h2>
        <p className="text-sm text-slate-500 mb-6">
          {t.selectRoleSubtitle}
        </p>

        <div className="space-y-2.5 max-h-[60vh] overflow-y-auto pr-1">
          {t.pharmaRoles.map((role, idx) => (
            <button
              key={idx}
              onClick={() => onSelectRole(role)}
              className="w-full text-left p-4 bg-slate-50 hover:bg-indigo-600 hover:text-white font-semibold rounded-xl border border-slate-200 transition-all text-sm cursor-pointer"
            >
              {role}
            </button>
          ))}
        </div>

        <button 
          onClick={onBack}
          className="w-full text-center text-xs text-slate-400 hover:text-indigo-600 mt-6 font-semibold transition-colors cursor-pointer"
        >
          ← {t.backToQuiz}
        </button>
      </div>
    </div>
  );
}

// 2. SCHERMATA CERTIFICATO FINALE, SALVATAGGIO FIRESTORE E INVIO MAIL
function FinalCertificateView({ leadData, onRestart }) {
  const lang = (leadData?.language || 'it').toLowerCase();

  React.useEffect(() => {
    if (!leadData) return;

    const saveAndSend = async () => {
      try {
        if (!window.firebase || !window.firebase.firestore) return;
        const db = window.firebase.firestore();

        const safeName = (leadData.name || "Anonimo").trim().replace(/\s+/g, '_');
        const safeSurname = (leadData.surname || "Lead").trim().replace(/\s+/g, '_');
        const customDocId = `${safeSurname}_${safeName}_${Date.now()}`;

        // Salva il Lead in Firestore
        await db.collection("lead_fiera_2026").doc(customDocId).set({
          ...leadData,
          createdAt: new Date()
        });

        const QUIZ_TITLES = { 
          q1: "Harmonised compliance", 
          q2: "OT Resilience & Integrity", 
          q3: "ESG & CSR", 
          q4: "Digital Validation", 
          q5: "Artificial Intelligence" 
        };
        const maxScores = { q1: 100, q2: 44, q3: 48, q4: 84, q5: 52 };
        const maxScore = maxScores[leadData.quizId] || 100;

        // Coda invio email automatica generica
        await db.collection("mailProva").add({
          to: leadData.email,
          message: {
            subject: lang === 'en' 
              ? `MAASI ENTERPRISES - Assessment Certificate - ${QUIZ_TITLES[leadData.quizId]}` 
              : `MAASI ENTERPRISES - Il tuo Attestato Assessment - ${QUIZ_TITLES[leadData.quizId]}`,
            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;">
                    ${lang === 'en' ? 'Assessment Completed!' : 'Assessment Completato!'}
                  </h2>
                </div>
                
                <p style="font-size: 15px; line-height: 1.5;">
                  ${lang === 'en' ? `Dear <b>${leadData.name}${leadData.surname}</b>,` : `Gentile <b>${leadData.name}${leadData.surname}</b>,`}
                </p>
                
                <p style="font-size: 15px; line-height: 1.5;">
                  ${lang === 'en' 
                    ? 'Thank you for visiting our stand. Here is the summary of your specialized assessment:' 
                    : 'Grazie per aver visitato il nostro stand. Di seguito trovi il riepilogo del tuo assessment 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[leadData.quizId]}</td>
                    </tr>
                    <tr>
                      <td style="padding: 6px 0; color: #64748b;"><b>${lang === 'en' ? 'Result Profile:' : 'Profilo Risultato:'}</b></td>
                      <td style="padding: 6px 0; color: #4f46e5; font-weight: bold;">${leadData.profileTitle}</td>
                    </tr>
                    <tr>
                      <td style="padding: 6px 0; color: #64748b;"><b>${lang === 'en' ? 'Total Score:' : 'Punteggio Totale:'}</b></td>
                      <td style="padding: 6px 0; color: #0f172a; font-weight: bold;">${leadData.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;">
                  ${leadData.profileDesc || ""}
                </p>

                <p style="font-size: 15px; line-height: 1.5; margin-top: 25px;">
                  ${lang === 'en' 
                    ? 'Our specialists remain at your complete disposal at the stand for further technical insights.' 
                    : 'I nostri specialists rimangono a tua completa disposizione allo stand per ulteriori approfondimenti tecnici.'}
                </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 | Automatic Compliance Assessment System
                </p>
              </div>
            `
          }
        });
      } catch (err) {
        console.error("Errore salvataggio final lead:", err);
      }
    };

    saveAndSend();
  }, [leadData, lang]);

  const certificatoHtml = window.generaHtmlCertificato(leadData);

  return (
    <div className="min-h-screen bg-slate-50 flex flex-col justify-between p-4 box-border animate-fadeIn">
      <div className="w-full max-w-2xl mx-auto bg-indigo-50 border border-indigo-100 p-3 rounded-xl text-center shadow-sm shrink-0">
        <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' 
            ? "Your assessment summary and certificate have been sent to your email!" 
            : "Il riepilogo dell'assessment e il certificato sono stati inviati alla tua email!"
          }
        </p>
      </div>

      <div className="flex-1 w-full max-w-4xl mx-auto flex items-center justify-center min-h-[350px] max-h-[60vh] 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-2 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>
  );
}

// 3. COMPONENTE PRINCIPALE CON GESTIONE ACCENTRATA DEL FLUSSO
function App() {
  const [appStep, setAppStep] = React.useState('dashboard');
  const [selectedQuizId, setSelectedQuizId] = React.useState(null);
  const [selectedRole, setSelectedRole] = React.useState('');
  const [quizResultData, setQuizResultData] = React.useState(null);
  const [finalUserData, setFinalUserData] = React.useState(null);

  const getAppLanguage = () => {
    const config = (window.APP_LANGUAGE_MODE || 'all').toLowerCase();
    return (config === 'en' || config === 'it') ? config : 'it';
  };

  const [currentLang, setCurrentLang] = React.useState(getAppLanguage());

  const urlParams = new URLSearchParams(window.location.search);
  const isCollegaView = urlParams.get('view') === 'lead';

  if (isCollegaView) {
    return <window.Dashboard />;
  }

  return (
    <div>
      {/* STEP 1: Dashboard Iniziale */}
      {appStep === 'dashboard' && (
        <Dashboard 
          user={{ language: currentLang }} 
          onSelectQuiz={(id) => { 
            setSelectedQuizId(id); 
            setAppStep('role_selection');
          }} 
        />
      )}

      {/* STEP 2: Scelta Ruolo */}
      {appStep === 'role_selection' && (
        <RoleSelectionModal 
          lang={currentLang}
          onSelectRole={(role) => {
            setSelectedRole(role);
            setAppStep('quiz_run');
          }}
          onBack={() => setAppStep('dashboard')}
        />
      )}
      
      {/* STEP 3: Quiz Engine */}
      {appStep === 'quiz_run' && (
        <QuizEngine 
          quizId={selectedQuizId} 
          lang={currentLang}
          user={{ role: selectedRole, language: currentLang }}
          onQuizCalculated={(scoreData) => { 
            setQuizResultData(scoreData);
            setAppStep('lead_capture'); 
          }} 
        />
      )}

      {/* STEP 4: Form Dati Utente */}
      {appStep === 'lead_capture' && (
        <AuthFlow 
          initialRole={selectedRole}
          onComplete={(formData) => { 
            const userLang = formData.language || currentLang;
            setCurrentLang(userLang);
            
            const fullLead = { 
              ...formData, 
              ...quizResultData, 
              language: userLang,
              quizId: selectedQuizId,
              quizTitle: { q1: "Harmonised compliance", q2: "OT Resilience & Integrity", q3: "ESG & CSR", q4: "Digital Validation", q5: "Artificial Intelligence" }[selectedQuizId]
            };
            setFinalUserData(fullLead);
            setAppStep('certificate_view'); 
          }} 
        />
      )}

      {/* STEP 5: Certificato e Reset */}
      {appStep === 'certificate_view' && (
        <FinalCertificateView 
          leadData={finalUserData}
          onRestart={() => {
            setSelectedQuizId(null); 
            setSelectedRole('');
            setQuizResultData(null);
            setFinalUserData(null);      
            setCurrentLang(getAppLanguage());
            setAppStep('dashboard');
          }}
        />
      )}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);