// src/components/AuthFlow.jsx

function AuthFlow({ onComplete }) {
  const lang = typeof APP_CONFIG !== 'undefined' && APP_CONFIG.enableItalian ? 'it' : (APP_CONFIG?.defaultLang || 'en');
  
  const [formData, setFormData] = React.useState({
    name: '',
    surname: '',
    email: '',
    company: '',
    phone: ''
  });
  const [errors, setErrors] = React.useState({});
  
  const [privacyAccepted, setPrivacyAccepted] = React.useState(false);
  const [showPrivacyModal, setShowPrivacyModal] = React.useState(false);

  // 🚀 TESTI AGGIORNATI CON LA NUOVA CALL TO ACTION DEI PREMI
  const t = typeof translations !== 'undefined' ? translations[lang] : {
    formTitle: lang === 'en' ? "Personalise your certificate" : "Personalizza il tuo certificato",
    formSubtitle: lang === 'en' 
      ? "Enter your details to receive a personalised certificate and enter the prize draw—where top scorers and wooden spooners both take home a prize!" 
      : "Inserisci i tuoi dati per ricevere un certificato personalizzato e partecipare all'estrazione finale: sia i punteggi più alti che quelli più bassi vinceranno un premio!",
    name: lang === 'en' ? "First Name" : "Nome",
    surname: lang === 'en' ? "Last Name" : "Cognome",
    email: lang === 'en' ? "Email Address" : "Indirizzo Email",
    company: lang === 'en' ? "Company Name" : "Nome Azienda",
    phone: lang === 'en' ? "Phone Number (Optional)" : "Contatto Telefonico (Facoltativo)",
    requiredField: lang === 'en' ? "This field is required" : "Questo campo è obbligatorio",
    invalidEmail: lang === 'en' ? "Enter a valid email address" : "Inserisci un indirizzo email valido",
    next: lang === 'en' ? "View Results" : "Vedi Risultati"
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    if (errors[name]) setErrors(prev => ({ ...prev, [name]: '' }));
  };

  const validateForm = () => {
    const newErrors = {};
    if (!formData.name.trim()) newErrors.name = t.requiredField;
    if (!formData.surname.trim()) newErrors.surname = t.requiredField;
    if (!formData.company.trim()) newErrors.company = t.requiredField;
    
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!formData.email.trim()) {
      newErrors.email = t.requiredField;
    } else if (!emailRegex.test(formData.email)) {
      newErrors.email = t.invalidEmail;
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!privacyAccepted) return;

    if (validateForm()) {
      onComplete({ ...formData, language: lang });
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-slate-50 px-4 py-12 sm:px-6 lg:px-8 text-slate-900">
      <div className="max-w-xl w-full bg-white border border-slate-200 p-8 rounded-3xl shadow-xl animate-slideUp">
        <div className="mb-8">
          <h2 className="text-3xl font-black text-slate-900 tracking-tight">{t.formTitle}</h2>
          <p className="text-sm text-slate-500 mt-2 leading-relaxed">{t.formSubtitle}</p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-5">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">{t.name} *</label>
              <input type="text" name="name" value={formData.name} onChange={handleChange} className={`w-full px-4 py-3 rounded-xl bg-slate-50 border ${errors.name ? 'border-red-500' : 'border-slate-200 focus:border-indigo-500'} text-slate-900 focus:outline-none focus:bg-white transition-all text-sm`} />
              {errors.name && <p className="text-red-600 font-medium text-xs mt-1.5">{errors.name}</p>}
            </div>
            <div>
              <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">{t.surname} *</label>
              <input type="text" name="surname" value={formData.surname} onChange={handleChange} className={`w-full px-4 py-3 rounded-xl bg-slate-50 border ${errors.surname ? 'border-red-500' : 'border-slate-200 focus:border-indigo-500'} text-slate-900 focus:outline-none focus:bg-white transition-all text-sm`} />
              {errors.surname && <p className="text-red-600 font-medium text-xs mt-1.5">{errors.surname}</p>}
            </div>
          </div>

          <div>
            <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">{t.email} *</label>
            <input type="email" name="email" value={formData.email} onChange={handleChange} className={`w-full px-4 py-3 rounded-xl bg-slate-50 border ${errors.email ? 'border-red-500' : 'border-slate-200 focus:border-indigo-500'} text-slate-900 focus:outline-none focus:bg-white transition-all text-sm`} />
            {errors.email && <p className="text-red-600 font-medium text-xs mt-1.5">{errors.email}</p>}
          </div>

          <div>
            <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">{t.company} *</label>
            <input type="text" name="company" value={formData.company} onChange={handleChange} className={`w-full px-4 py-3 rounded-xl bg-slate-50 border ${errors.company ? 'border-red-500' : 'border-slate-200 focus:border-indigo-500'} text-slate-900 focus:outline-none focus:bg-white transition-all text-sm`} />
            {errors.company && <p className="text-red-600 font-medium text-xs mt-1.5">{errors.company}</p>}
          </div>

          <div>
            <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">{t.phone}</label>
            <input type="tel" name="phone" inputMode="tel" pattern="[\+0-9\s\-]*" value={formData.phone} onChange={handleChange} 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>

          <div className="mt-6 p-4 bg-slate-50 border border-slate-200 rounded-xl text-left shadow-inner">
            <label className="flex items-start gap-3 cursor-pointer select-none">
              <input type="checkbox" checked={privacyAccepted} onChange={(e) => setPrivacyAccepted(e.target.checked)} className="mt-1 w-4 h-4 text-indigo-600 bg-white border-slate-300 rounded focus:ring-indigo-500 focus:ring-2 cursor-pointer transition-all" />
              <span className="text-xs text-slate-600 leading-relaxed font-medium">
                {lang === 'en' ? (
                  <>I have read and understood the <span onClick={(e) => { e.preventDefault(); setShowPrivacyModal(true); }} className="text-indigo-600 underline hover:text-indigo-700 font-bold cursor-pointer">Privacy Notice</span>. I agree to the processing of my personal details for the assessment, readiness score, and certificate via email.</>
                ) : (
                  <>Ho preso visione dell'<span onClick={(e) => { e.preventDefault(); setShowPrivacyModal(true); }} className="text-indigo-600 underline hover:text-indigo-700 font-bold cursor-pointer">Informativa Privacy</span> e acconsento al trattamento dei miei dati personali per l'elaborazione del test, del readiness score e l'invio del certificato via email.</>
                )}
              </span>
            </label>
          </div>

          <button type="submit" disabled={!privacyAccepted} className={`w-full mt-4 font-bold py-4 px-6 rounded-xl transition-all duration-300 text-center tracking-wide ${privacyAccepted ? "bg-indigo-600 text-white shadow-md hover:bg-indigo-700 transform hover:-translate-y-0.5 cursor-pointer" : "bg-slate-100 text-slate-400 cursor-not-allowed opacity-70"}`}>
            {t.next}
          </button>
        </form>
      </div>

      {showPrivacyModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm animate-fadeIn">
          <div className="bg-white border border-slate-200 max-w-4xl w-full h-[85vh] flex flex-col rounded-3xl shadow-2xl overflow-hidden animate-scaleUp">
            <div className="p-6 border-b border-slate-200 flex justify-between items-center bg-slate-50">
              <h3 className="text-xl font-bold text-slate-900 tracking-tight">{lang === 'en' ? "Privacy Policy" : "Informativa Privacy"}</h3>
              <button onClick={() => setShowPrivacyModal(false)} className="text-slate-400 hover:text-slate-700 text-2xl font-mono cursor-pointer p-1">✕</button>
            </div>
            <div className="flex-1 bg-slate-100 p-2">
              <iframe src="/privacy-test.pdf" className="w-full h-full rounded-xl border border-slate-200 bg-white" title="Privacy Policy"></iframe>
            </div>
            <div className="p-4 border-t border-slate-200 bg-slate-50 flex justify-end">
              <button onClick={() => setShowPrivacyModal(false)} className="px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-xl text-sm shadow-sm transition-all cursor-pointer">
                {lang === 'en' ? "Close and Return" : "Chiudi e Ritorna"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.AuthFlow = AuthFlow;