// js/quiz.jsx — 8-question quiz experience

const QUESTIONS = [
  {
    id: 'q1',
    label: '01 —',
    text: 'Combien de logements gérez-vous en location courte durée ?',
    type: 'single',
    options: ['1 logement','2 à 4 logements','5 à 9 logements','10 logements et plus'],
  },
  {
    id: 'q2',
    label: '02 —',
    text: 'Sur quelles plateformes êtes-vous actuellement présent ?',
    type: 'multi',
    options: ['Airbnb','Booking.com','Abritel / Vrbo','Site de réservation direct','Autres'],
  },
  {
    id: 'q3',
    label: '03 —',
    text: 'Quel est votre taux d\'occupation moyen sur les 3 derniers mois ?',
    type: 'single',
    options: ['Moins de 50%','Entre 50% et 70%','Entre 70% et 85%','Plus de 85%'],
  },
  {
    id: 'q4',
    label: '04 —',
    text: 'Comment fixez-vous vos tarifs ?',
    type: 'single',
    options: ['Un prix fixe toute l\'année','Je varie manuellement selon les saisons','J\'utilise un outil de pricing dynamique','Je m\'adapte au marché mais sans outil précis'],
  },
  {
    id: 'q5',
    label: '05 —',
    text: 'Qu\'est-ce que vos voyageurs reçoivent actuellement à leur arrivée ?',
    type: 'single',
    options: ['Un message automatique Airbnb avec les informations de base','Un guide maison que j\'ai créé moi-même (PDF ou Notion)','Un guestbook digital avec toutes les informations','Rien de particulier, ils me contactent si besoin'],
  },
  {
    id: 'q6',
    label: '06 —',
    text: 'Proposez-vous des services supplémentaires à vos voyageurs (en dehors de la nuitée) ?',
    type: 'single',
    options: ['Non, je n\'y ai pas pensé','Parfois, de manière informelle','Oui, j\'ai quelques services disponibles mais peu sollicités','Oui, j\'ai un système structuré d\'upsell'],
  },
  {
    id: 'q7',
    label: '07 —',
    text: 'Qu\'est-ce qui vous empêche d\'aller plus loin dans l\'optimisation de votre location ?',
    type: 'single',
    options: ['Le manque de temps','Le manque de compétences techniques','Je ne sais pas par où commencer','Je pensais que ça nécessitait un gros investissement'],
  },
  {
    id: 'q8',
    label: '08 —',
    text: 'Pour recevoir votre diagnostic personnalisé :',
    type: 'email',
  },
];

// ─── Particle background ─────────────────────────────────────────────
const Particles = () => {
  const particles = React.useMemo(() =>
    Array.from({ length: 28 }, (_, i) => ({
      id: i,
      left: Math.random() * 100,
      top: Math.random() * 100,
      size: 1 + Math.random() * 2,
      dx: (Math.random() - 0.5) * 120,
      dy: -40 - Math.random() * 100,
      duration: 8 + Math.random() * 12,
      delay: Math.random() * 8,
    })), []);

  return (
    <div style={{ position:'absolute', inset:0, pointerEvents:'none', overflow:'hidden', zIndex:0 }}>
      {particles.map(p => (
        <div key={p.id} style={{
          position:'absolute',
          left: p.left + '%',
          top: p.top + '%',
          width: p.size,
          height: p.size,
          borderRadius: '50%',
          background: 'rgba(59,123,246,0.5)',
          animation: `particleDrift ${p.duration}s ${p.delay}s ease-in-out infinite`,
          '--dx': p.dx + 'px',
          '--dy': p.dy + 'px',
        }} />
      ))}
    </div>
  );
};

// ─── Quiz option card ────────────────────────────────────────────────
const OptionCard = ({ label, selected, onClick, accent }) => {
  const [hov, setHov] = React.useState(false);
  return (
    <div
      onClick={onClick}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        background: selected ? `${accent}18` : hov ? 'rgba(255,255,255,.07)' : 'rgba(255,255,255,.04)',
        border: `1.5px solid ${selected ? accent : hov ? accent+'66' : 'rgba(255,255,255,.1)'}`,
        borderRadius: 14,
        padding: '18px 24px',
        cursor: 'pointer',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        gap: 16,
        transition: 'all .18s cubic-bezier(.34,1.56,.64,1)',
        transform: selected ? 'scale(1.01)' : hov ? 'scale(1.005)' : 'scale(1)',
        userSelect: 'none',
      }}
    >
      <span style={{ fontSize: 15, fontWeight: 500, color: selected ? '#fff' : '#CBD5E1', lineHeight: 1.45, fontFamily: 'Inter, sans-serif' }}>{label}</span>
      {selected && (
        <div style={{
          width: 24, height: 24, borderRadius: '50%',
          background: `linear-gradient(135deg, ${accent}, #1a4fd6)`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
          animation: 'fadeIn .2s ease',
        }}>
          <svg width="12" height="9" viewBox="0 0 12 9" fill="none">
            <path d="M1 4L4.5 7.5L11 1" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
      )}
    </div>
  );
};

// ─── Main Quiz Page ───────────────────────────────────────────────────
const QuizPage = ({ onComplete }) => {
  const { useTweaks, CTAButton } = window;
  const { accent } = useTweaks();
  const [current, setCurrent] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [animState, setAnimState] = React.useState('in'); // 'in' | 'out'
  const [firstName, setFirstName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [submitState, setSubmitState] = React.useState('idle'); // 'idle' | 'loading' | 'analysing'

  const q = QUESTIONS[current];
  const progress = ((current) / QUESTIONS.length) * 100;

  const goNext = () => {
    setAnimState('out');
    setTimeout(() => {
      setCurrent(c => c + 1);
      setAnimState('in');
    }, 380);
  };

  const selectOption = (opt) => {
    if (q.type === 'single') {
      setAnswers(a => ({ ...a, [q.id]: opt }));
      setTimeout(() => goNext(), 400);
    } else {
      setAnswers(a => {
        const cur = a[q.id] || [];
        return { ...a, [q.id]: cur.includes(opt) ? cur.filter(x => x !== opt) : [...cur, opt] };
      });
    }
  };

  const handleSubmit = () => {
    if (!email || !firstName) return;
    setSubmitState('loading');
    setTimeout(() => {
      setSubmitState('analysing');
      setTimeout(() => {
        onComplete({ ...answers, firstName, email, phone });
      }, 2200);
    }, 1400);
  };

  const canContinueMulti = q.type === 'multi' && (answers[q.id] || []).length > 0;

  return (
    <div style={{
      minHeight: '100vh',
      background: 'radial-gradient(ellipse 80% 70% at 50% 40%, #162B52 0%, #0A1628 80%)',
      display: 'flex',
      flexDirection: 'column',
      position: 'relative',
      overflow: 'hidden',
    }}>
      <Particles />

      {/* Top bar */}
      <div style={{ padding: '24px 40px 0', position: 'relative', zIndex: 2 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', maxWidth: 720, margin: '0 auto', marginBottom: 12 }}>
          <div style={{ fontFamily: 'Plus Jakarta Sans, sans-serif', fontWeight: 800, fontSize: 18, color: '#fff' }}>Go<span style={{ color: accent }}>Rently</span></div>
          <div style={{ fontSize: 13, color: '#94A3B8', fontWeight: 500 }}>
            Question <span style={{ color: '#fff', fontWeight: 700 }}>{Math.min(current + 1, 8)}</span>/8
          </div>
        </div>
        {/* Progress bar */}
        <div style={{ maxWidth: 720, margin: '0 auto' }}>
          <div style={{ height: 3, background: 'rgba(255,255,255,.08)', borderRadius: 3, overflow: 'hidden' }}>
            <div style={{
              height: '100%',
              background: `linear-gradient(90deg, ${accent}, #93B8FF)`,
              borderRadius: 3,
              width: progress + '%',
              transition: 'width .5s cubic-bezier(.4,0,.2,1)',
              boxShadow: `0 0 10px ${accent}88`,
            }} />
          </div>
        </div>
      </div>

      {/* Question area */}
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'clamp(24px,5vw,40px) clamp(16px,4vw,40px)', position: 'relative', zIndex: 2 }}>
        <div style={{
          width: '100%', maxWidth: 680,
          animation: animState === 'in' ? 'quizSlideIn .38s cubic-bezier(.34,1.3,.64,1) both' : 'quizSlideOut .32s ease both',
        }}>
          {/* Email/name step */}
          {q.type === 'email' ? (
            <div>
              <div style={{ fontSize: 13, color: accent, fontWeight: 700, letterSpacing: '1.5px', textTransform: 'uppercase', marginBottom: 16 }}>{q.label}</div>
              <h2 style={{ fontFamily: 'Plus Jakarta Sans, sans-serif', fontWeight: 800, fontSize: 30, color: '#fff', marginBottom: 36, lineHeight: 1.25, textWrap: 'balance' }}>{q.text}</h2>

              {submitState === 'analysing' ? (
                <div style={{ textAlign: 'center', padding: '40px 0' }}>
                  <div style={{ marginBottom: 24, fontSize: 32 }}>🔍</div>
                  <div style={{ fontFamily: 'Plus Jakarta Sans, sans-serif', fontWeight: 700, fontSize: 22, color: '#fff', marginBottom: 12 }}>Analyse en cours…</div>
                  <div style={{ color: '#94A3B8', fontSize: 15, marginBottom: 32 }}>Nous préparons votre diagnostic personnalisé</div>
                  <div style={{ maxWidth: 320, margin: '0 auto', height: 4, background: 'rgba(255,255,255,.08)', borderRadius: 4, overflow: 'hidden' }}>
                    <div style={{ height: '100%', background: `linear-gradient(90deg,${accent},#93B8FF)`, borderRadius: 4, animation: 'progressFill 2s linear forwards' }} />
                  </div>
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                  <input
                    type="text"
                    placeholder="Prénom"
                    value={firstName}
                    onChange={e => setFirstName(e.target.value)}
                    style={{ width: '100%', background: 'rgba(255,255,255,.06)', border: '1.5px solid rgba(255,255,255,.12)', borderRadius: 12, padding: '16px 20px', fontSize: 15, color: '#fff', fontFamily: 'Inter, sans-serif', outline: 'none' }}
                    onFocus={e => e.target.style.borderColor = accent}
                    onBlur={e => e.target.style.borderColor = 'rgba(255,255,255,.12)'}
                  />
                  <input
                    type="email"
                    placeholder="Email *"
                    value={email}
                    onChange={e => setEmail(e.target.value)}
                    style={{ width: '100%', background: 'rgba(255,255,255,.06)', border: '1.5px solid rgba(255,255,255,.12)', borderRadius: 12, padding: '16px 20px', fontSize: 15, color: '#fff', fontFamily: 'Inter, sans-serif', outline: 'none' }}
                    onFocus={e => e.target.style.borderColor = accent}
                    onBlur={e => e.target.style.borderColor = 'rgba(255,255,255,.12)'}
                  />
                  <input
                    type="tel"
                    placeholder="WhatsApp (optionnel)"
                    value={phone}
                    onChange={e => setPhone(e.target.value)}
                    style={{ width: '100%', background: 'rgba(255,255,255,.06)', border: '1.5px solid rgba(255,255,255,.12)', borderRadius: 12, padding: '16px 20px', fontSize: 15, color: '#fff', fontFamily: 'Inter, sans-serif', outline: 'none' }}
                    onFocus={e => e.target.style.borderColor = accent}
                    onBlur={e => e.target.style.borderColor = 'rgba(255,255,255,.12)'}
                  />
                  <p style={{ fontSize: 12, color: '#4A6080', lineHeight: 1.6 }}>En soumettant ce formulaire, vous acceptez de recevoir votre diagnostic par email. Aucun démarchage commercial. Désabonnement en un clic.</p>
                  <CTAButton
                    onClick={handleSubmit}
                    size="large"
                    fullWidth
                    style={{ marginTop: 8, opacity: (!email || !firstName) ? 0.5 : 1 }}
                  >
                    {submitState === 'loading' ? (
                      <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10 }}>
                        <span style={{ width: 18, height: 18, border: '2px solid rgba(255,255,255,.3)', borderTopColor: '#fff', borderRadius: '50%', display: 'inline-block', animation: 'spin .7s linear infinite' }} />
                        Envoi…
                      </span>
                    ) : 'Voir mon diagnostic →'}
                  </CTAButton>
                </div>
              )}
            </div>
          ) : (
            <div>
              <div style={{ fontSize: 13, color: accent, fontWeight: 700, letterSpacing: '1.5px', textTransform: 'uppercase', marginBottom: 16 }}>{q.label}</div>
              <h2 style={{ fontFamily: 'Plus Jakarta Sans, sans-serif', fontWeight: 800, fontSize: 30, color: '#fff', marginBottom: 32, lineHeight: 1.25, textWrap: 'balance' }}>{q.text}</h2>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {q.options.map((opt, i) => {
                  const sel = q.type === 'multi'
                    ? (answers[q.id] || []).includes(opt)
                    : answers[q.id] === opt;
                  return (
                    <div key={i} style={{ animation: `fadeInUp .35s ${i * .06}s both` }}>
                      <OptionCard label={opt} selected={sel} onClick={() => selectOption(opt)} accent={accent} />
                    </div>
                  );
                })}
              </div>

              {q.type === 'multi' && (
                <div style={{ marginTop: 24, textAlign: 'center' }}>
                  <CTAButton onClick={goNext} style={{ opacity: canContinueMulti ? 1 : 0.4 }}>
                    Continuer →
                  </CTAButton>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { QuizPage });
