// ═══════════════════════════════════════════════════════════════════════════
//  QUIZ 8BAC — capa + 3 perguntas + popup de captura
// ═══════════════════════════════════════════════════════════════════════════

const QUIZ_LABELS = {
  tem_trafego: { sim: 'Sim, já invisto/investi', nao: 'Não, ainda não' },
  faturamento: {
    'ate-30k':  'Até R$ 30 mil',
    '30-60k':   'R$ 30 a 60 mil',
    '60-150k':  'R$ 60 a 150 mil',
    '150k+':    'R$ 150 mil ou mais',
  },
  atendimento: { ligacao: 'Ligação', mensagem: 'Mensagem', video: 'Vídeo-chamada' },
};

function Quiz({ onCapture, onClose, originText, mode }) {
  const isOverlay = mode === 'overlay';
  const [step, setStep]           = React.useState(0); // 0=capa, 1..3=perguntas
  const [modalOpen, setModalOpen] = React.useState(false);
  const [answers, setAnswers]     = React.useState({ tem_trafego: '', faturamento: '', atendimento: '' });

  React.useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  }, [step, modalOpen]);

  React.useEffect(() => {
    if (isOverlay) {
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = ''; };
    }
  }, [isOverlay]);

  function startQuiz() {
    fireCustom('QuizStart');
    setStep(1);
  }

  function pickAnswer(key, value, eventName) {
    setAnswers(a => ({ ...a, [key]: value }));
    fireCustom(eventName, { [key]: value });
    const next = step + 1;
    setTimeout(() => {
      if (next <= 3) setStep(next);
      else setModalOpen(true);
    }, 380);
  }

  return (
    <div className={'quiz' + (isOverlay ? ' quiz--overlay' : '')}>
      <header className="quiz__bar">
        <div className="quiz__logo">
          <span style={{ color: 'var(--bac-blue)' }}>8</span>
          <span style={{ color: 'var(--bac-navy)' }}>BAC</span>
        </div>
        {onClose && (
          <button className="quiz__close" onClick={onClose} aria-label="Fechar">
            <i data-lucide="x" style={{ width: 18, height: 18 }}></i>
          </button>
        )}
      </header>

      <main className="quiz__main">
        {step === 0 && <Cover onStart={startQuiz} />}

        {step === 1 && (
          <Question
            key="q1"
            current={1} total={3}
            label="Você já investe ou já investiu em tráfego?"
            options={[
              { value: 'sim', label: 'Sim', icon: 'check-circle' },
              { value: 'nao', label: 'Não', icon: 'x-circle' },
            ]}
            selected={answers.tem_trafego}
            onAnswer={v => pickAnswer('tem_trafego', v, 'QuizStep_TemTrafego')}
          />
        )}

        {step === 2 && (
          <Question
            key="q2"
            current={2} total={3}
            label="Hoje você fatura em média?"
            sub="O faturamento é super importante para entendermos a melhor estratégia."
            options={[
              { value: 'ate-30k', label: 'Até R$ 30 mil',         icon: 'sprout' },
              { value: '30-60k',  label: 'R$ 30 a 60 mil',        icon: 'trending-up' },
              { value: '60-150k', label: 'R$ 60 a 150 mil',       icon: 'rocket' },
              { value: '150k+',   label: 'R$ 150 mil ou mais',    icon: 'crown' },
            ]}
            selected={answers.faturamento}
            onAnswer={v => pickAnswer('faturamento', v, 'QuizStep_Faturamento')}
          />
        )}

        {step === 3 && (
          <Question
            key="q3"
            current={3} total={3}
            label="Como você prefere seu atendimento?"
            options={[
              { value: 'ligacao',  label: 'Ligação',        icon: 'phone' },
              { value: 'mensagem', label: 'Mensagem',       icon: 'message-circle' },
              { value: 'video',    label: 'Vídeo-chamada',  icon: 'video' },
            ]}
            selected={answers.atendimento}
            onAnswer={v => pickAnswer('atendimento', v, 'QuizStep_Atendimento')}
          />
        )}
      </main>

      {modalOpen && (
        <Modal
          answers={answers}
          originText={originText}
          onClose={() => setModalOpen(false)}
          onSubmit={onCapture}
        />
      )}

      <style>{`
        .quiz {
          min-height: 100vh; min-height: 100dvh;
          background: var(--bg-alt);
          display: flex; flex-direction: column;
        }
        .quiz--overlay {
          position: fixed; inset: 0; z-index: 90;
          animation: quizOverlayIn .26s var(--ease-out);
          overflow-y: auto;
        }
        @keyframes quizOverlayIn {
          from { opacity: 0; transform: translateY(8px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        .quiz__bar {
          padding: 18px 20px;
          display: flex; align-items: center; justify-content: center;
          background: #fff; border-bottom: 1px solid var(--line);
          position: relative;
        }
        .quiz__logo {
          font-family: var(--font-display); font-weight: 900;
          font-size: 22px; line-height: 1; letter-spacing: -0.04em;
        }
        .quiz__close {
          position: absolute; top: 50%; right: 16px; transform: translateY(-50%);
          width: 36px; height: 36px; border-radius: 8px;
          background: var(--bg-alt); border: 1px solid var(--line);
          display: flex; align-items: center; justify-content: center;
          cursor: pointer; color: var(--ink-3);
          -webkit-tap-highlight-color: transparent;
        }
        .quiz__close:hover { background: var(--line); }
        .quiz__main {
          flex: 1;
          display: flex; align-items: center; justify-content: center;
          padding: 24px 20px 40px;
        }
        @media (min-width: 720px) {
          .quiz__bar { padding: 20px 24px; }
          .quiz__logo { font-size: 26px; }
          .quiz__close { right: 24px; }
          .quiz__main { padding: 48px 24px; }
        }
      `}</style>
    </div>
  );
}

// ─── CAPA ────────────────────────────────────────────────────────────────────
function Cover({ onStart }) {
  return (
    <section className="cover" aria-labelledby="cover-title">
      <div className="cover__chip">
        <span className="cover__dot"></span>
        DIAGNÓSTICO ESTRATÉGICO · 30 SEGUNDOS
      </div>

      <h1 id="cover-title" className="cover__title">
        Bora! Vamos começar.
      </h1>

      <p className="cover__sub">
        Vou te fazer <strong>3 perguntas rapidinho</strong> antes da
        gente conversar — é o jeito mais rápido de eu já chegar
        com a estratégia certa pro seu negócio.
      </p>

      <button className="cover__btn" onClick={onStart}>
        Iniciar
        <i data-lucide="arrow-right" style={{ width: 20, height: 20 }}></i>
      </button>

      <div className="cover__trust">
        <i data-lucide="shield-check" style={{ width: 12, height: 12 }}></i>
        Seus dados são protegidos · sem spam
      </div>

      <style>{`
        .cover {
          width: 100%; max-width: 560px;
          display: flex; flex-direction: column; align-items: center;
          text-align: center;
          animation: fadeUp .42s var(--ease-out);
        }
        @keyframes fadeUp {
          from { opacity: 0; transform: translateY(16px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        .cover__chip {
          font-family: var(--font-mono); font-size: 11px; font-weight: 600;
          letter-spacing: 0.06em; color: var(--bac-blue);
          background: rgba(0,102,254,.08);
          padding: 8px 14px; border-radius: 999px;
          display: inline-flex; align-items: center; gap: 8px;
          margin-bottom: 28px;
        }
        .cover__dot {
          width: 6px; height: 6px; border-radius: 50%;
          background: var(--bac-blue);
          animation: pulse 1.6s ease-in-out infinite;
        }
        @keyframes pulse {
          0%,100% { opacity: 1; transform: scale(1); }
          50%     { opacity: .55; transform: scale(.9); }
        }
        .cover__title {
          font-family: var(--font-display); font-weight: 900;
          font-size: clamp(36px, 9vw, 64px); line-height: 1.02;
          letter-spacing: -0.035em; color: var(--ink-1);
          margin: 0 0 18px 0;
        }
        .cover__sub {
          font-family: var(--font-sans); font-size: 17px; line-height: 1.55;
          color: var(--ink-3); margin: 0 0 36px 0; max-width: 460px;
        }
        .cover__sub strong { color: var(--ink-1); font-weight: 700; }
        .cover__btn {
          display: inline-flex; align-items: center; justify-content: center; gap: 10px;
          background: var(--bac-blue); color: #fff;
          font-family: var(--font-sans); font-weight: 700; font-size: 17px;
          padding: 20px 36px; border-radius: 14px; border: 0; cursor: pointer;
          width: 100%; max-width: 360px;
          box-shadow: 0 12px 32px rgba(0,102,254,.32);
          transition: all .16s var(--ease-out);
          -webkit-tap-highlight-color: transparent;
          min-height: 60px;
        }
        .cover__btn:hover  { background: var(--bac-blue-700); transform: translateY(-2px); box-shadow: 0 16px 40px rgba(0,102,254,.4); }
        .cover__btn:active { transform: translateY(0); }
        .cover__trust {
          font-family: var(--font-mono); font-size: 11px; font-weight: 600;
          letter-spacing: 0.04em; color: var(--ink-4);
          margin-top: 22px;
          display: inline-flex; align-items: center; gap: 6px;
        }
        @media (min-width: 720px) {
          .cover__sub { font-size: 19px; }
        }
      `}</style>
    </section>
  );
}

// ─── PERGUNTA ────────────────────────────────────────────────────────────────
function Question({ current, total, label, sub, options, selected, onAnswer }) {
  const [picked, setPicked] = React.useState('');

  function handlePick(v) {
    if (picked) return; // evita duplo clique
    setPicked(v);
    onAnswer(v);
  }

  const pct = (current / total) * 100;

  return (
    <section className="qz" aria-labelledby="qz-title">
      <div className="qz__progress">
        <div className="qz__progress-meta">
          <span className="qz__step">PERGUNTA {current} DE {total}</span>
          <span className="qz__pct">{Math.round(pct)}%</span>
        </div>
        <div className="qz__bar"><div className="qz__bar-fill" style={{ width: `${pct}%` }}></div></div>
      </div>

      <h2 id="qz-title" className="qz__title">{label}</h2>
      {sub && <p className="qz__sub">{sub}</p>}

      <div className="qz__options">
        {options.map(opt => (
          <button
            key={opt.value}
            className={'qz__opt' + (picked === opt.value ? ' qz__opt--picked' : '')}
            onClick={() => handlePick(opt.value)}
            disabled={!!picked}
          >
            {opt.icon && (
              <span className="qz__opt-icon">
                <i data-lucide={opt.icon} style={{ width: 22, height: 22 }}></i>
              </span>
            )}
            <span className="qz__opt-label">{opt.label}</span>
            <span className="qz__opt-arrow">
              <i data-lucide={picked === opt.value ? 'check' : 'arrow-right'} style={{ width: 18, height: 18 }}></i>
            </span>
          </button>
        ))}
      </div>

      <style>{`
        .qz {
          width: 100%; max-width: 560px;
          animation: qFadeUp .4s var(--ease-out);
        }
        @keyframes qFadeUp {
          from { opacity: 0; transform: translateY(20px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        .qz__progress { margin-bottom: 28px; }
        .qz__progress-meta {
          display: flex; align-items: center; justify-content: space-between;
          margin-bottom: 8px;
        }
        .qz__step {
          font-family: var(--font-mono); font-size: 11px; font-weight: 600;
          letter-spacing: 0.08em; color: var(--bac-blue);
        }
        .qz__pct {
          font-family: var(--font-mono); font-size: 11px; font-weight: 600;
          letter-spacing: 0.04em; color: var(--ink-4);
        }
        .qz__bar {
          width: 100%; height: 6px; border-radius: 999px;
          background: var(--line); overflow: hidden;
        }
        .qz__bar-fill {
          height: 100%; background: var(--bac-blue);
          border-radius: 999px;
          transition: width .42s var(--ease-out);
        }
        .qz__title {
          font-family: var(--font-display); font-weight: 900;
          font-size: clamp(26px, 6.4vw, 38px); line-height: 1.1;
          letter-spacing: -0.025em; color: var(--ink-1);
          margin: 0 0 10px 0;
        }
        .qz__sub {
          font-family: var(--font-sans); font-size: 15px; line-height: 1.55;
          color: var(--ink-3); margin: 0 0 28px 0;
        }
        .qz__options { display: flex; flex-direction: column; gap: 12px; margin-top: 28px; }
        .qz__opt {
          display: flex; align-items: center; gap: 14px;
          padding: 18px 18px; border-radius: 14px;
          background: #fff; border: 2px solid var(--line);
          font-family: var(--font-sans); font-weight: 600; font-size: 16px;
          color: var(--ink-1); cursor: pointer; text-align: left;
          transition: all .16s var(--ease-out);
          -webkit-tap-highlight-color: transparent;
          min-height: 64px; width: 100%;
        }
        .qz__opt:hover:not(:disabled) {
          border-color: var(--bac-blue); transform: translateY(-1px);
          box-shadow: 0 4px 16px rgba(0,102,254,.08);
        }
        .qz__opt:active:not(:disabled) { transform: translateY(0); }
        .qz__opt:disabled { cursor: default; opacity: .55; }
        .qz__opt--picked, .qz__opt--picked:disabled {
          border-color: var(--bac-blue); background: rgba(0,102,254,.06);
          opacity: 1;
          box-shadow: 0 0 0 4px rgba(0,102,254,.12);
        }
        .qz__opt-icon {
          width: 40px; height: 40px; border-radius: 10px;
          background: rgba(0,102,254,.08); color: var(--bac-blue);
          display: flex; align-items: center; justify-content: center; flex-shrink: 0;
        }
        .qz__opt--picked .qz__opt-icon { background: var(--bac-blue); color: #fff; }
        .qz__opt-label { flex: 1; }
        .qz__opt-arrow {
          color: var(--ink-4); display: flex; align-items: center; flex-shrink: 0;
          transition: transform .16s var(--ease-out);
        }
        .qz__opt:hover:not(:disabled) .qz__opt-arrow { transform: translateX(4px); color: var(--bac-blue); }
        .qz__opt--picked .qz__opt-arrow { color: var(--bac-blue); }
        @media (min-width: 720px) {
          .qz__sub { font-size: 17px; }
          .qz__opt { padding: 20px 22px; font-size: 17px; min-height: 72px; }
        }
      `}</style>
    </section>
  );
}
