// ═══════════════════════════════════════════════════════════════════════════
//  MODAL DE CAPTURA — final do quiz, dispara Lead + Contact + redireciona pro WhatsApp
// ═══════════════════════════════════════════════════════════════════════════

function Modal({ answers, onClose, onSubmit, originText }) {
  const [form, setForm] = React.useState({
    nome: '', sobrenome: '', whatsapp: '', email: '', nascimento: ''
  });
  const [errors, setErrors] = React.useState({});
  const [loading, setLoading] = React.useState(false);

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

  React.useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  });

  function maskPhone(val) {
    const d = val.replace(/\D/g, '').slice(0, 11);
    if (d.length <= 2)  return d;
    if (d.length <= 7)  return `(${d.slice(0,2)}) ${d.slice(2)}`;
    if (d.length <= 11) return `(${d.slice(0,2)}) ${d.slice(2,7)}-${d.slice(7)}`;
    return val;
  }
  function maskDate(val) {
    const d = val.replace(/\D/g, '').slice(0, 8);
    if (d.length <= 2) return d;
    if (d.length <= 4) return `${d.slice(0,2)}/${d.slice(2)}`;
    return `${d.slice(0,2)}/${d.slice(2,4)}/${d.slice(4)}`;
  }

  function validate() {
    const e = {};
    if (!form.nome.trim() || form.nome.trim().length < 2)         e.nome = 'Informe seu nome.';
    if (!form.sobrenome.trim() || form.sobrenome.trim().length < 2) e.sobrenome = 'Informe seu sobrenome.';
    const digits = form.whatsapp.replace(/\D/g, '');
    if (digits.length < 10) e.whatsapp = 'WhatsApp inválido.';
    if (!form.email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'E-mail inválido.';
    const dd = form.nascimento.replace(/\D/g, '');
    if (dd.length !== 8) e.nascimento = 'Data inválida (DD/MM/AAAA).';
    return e;
  }

  async function handleSubmit(e) {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length) { setErrors(errs); return; }
    setLoading(true);

    const payload = { ...form, ...answers };
    await onSubmit(payload);

    // Monta a mensagem do WhatsApp com TODAS as respostas pra IA já saber tudo
    const labels = QUIZ_LABELS;
    const opener = originText || 'Olá! Vim do diagnóstico 8BAC 👋';
    const txt = [
      opener,
      '',
      `Sou o(a) *${form.nome.trim()} ${form.sobrenome.trim()}*`,
      `📧 ${form.email.trim()}`,
      `🎂 ${form.nascimento}`,
      '',
      '*Minhas respostas:*',
      `✓ Já investi em tráfego: ${labels.tem_trafego[answers.tem_trafego] || answers.tem_trafego}`,
      `✓ Faturamento atual: ${labels.faturamento[answers.faturamento] || answers.faturamento}`,
      `✓ Atendimento preferido: ${labels.atendimento[answers.atendimento] || answers.atendimento}`,
      '',
      'Quero entender como vocês podem me ajudar.'
    ].join('\n');

    const link = `https://wa.me/5513981773862?text=${encodeURIComponent(txt)}`;
    window.open(link, '_blank');
    onClose();
  }

  function set(field) {
    return (e) => {
      let val = e.target.value;
      if (field === 'whatsapp')   val = maskPhone(val);
      if (field === 'nascimento') val = maskDate(val);
      setForm(f => ({ ...f, [field]: val }));
      if (errors[field]) setErrors(er => ({ ...er, [field]: undefined }));
    };
  }

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-card" onClick={ev => ev.stopPropagation()}>

        <button className="modal-close" onClick={onClose} aria-label="Fechar">
          <i data-lucide="x" style={{ width: 18, height: 18 }}></i>
        </button>

        <div className="modal-chip">
          <i data-lucide="check-circle" style={{ width: 13, height: 13 }}></i>
          TUDO ANOTADO
        </div>

        <h2 className="modal-title">
          Pra garantir sua vaga,<br/>
          <span style={{ color: 'var(--bac-blue)' }}>confirma esses dados:</span>
        </h2>

        <form className="modal-form" onSubmit={handleSubmit} noValidate>

          <div className="modal-row">
            <div className="modal-field">
              <label className="modal-label">Nome <span className="modal-req">*</span></label>
              <input
                className={'modal-input' + (errors.nome ? ' modal-input--err' : '')}
                type="text" placeholder="João"
                value={form.nome} onChange={set('nome')}
                autoComplete="given-name" autoFocus
              />
              {errors.nome && <span className="modal-err-msg">{errors.nome}</span>}
            </div>

            <div className="modal-field">
              <label className="modal-label">Sobrenome <span className="modal-req">*</span></label>
              <input
                className={'modal-input' + (errors.sobrenome ? ' modal-input--err' : '')}
                type="text" placeholder="Silva"
                value={form.sobrenome} onChange={set('sobrenome')}
                autoComplete="family-name"
              />
              {errors.sobrenome && <span className="modal-err-msg">{errors.sobrenome}</span>}
            </div>
          </div>

          <div className="modal-field">
            <label className="modal-label">Seu WhatsApp <span className="modal-req">*</span></label>
            <input
              className={'modal-input' + (errors.whatsapp ? ' modal-input--err' : '')}
              type="tel" placeholder="(11) 99999-9999"
              value={form.whatsapp} onChange={set('whatsapp')}
              autoComplete="tel" inputMode="numeric"
            />
            {errors.whatsapp && <span className="modal-err-msg">{errors.whatsapp}</span>}
          </div>

          <div className="modal-field">
            <label className="modal-label">Seu melhor e-mail <span className="modal-req">*</span></label>
            <input
              className={'modal-input' + (errors.email ? ' modal-input--err' : '')}
              type="email" placeholder="joao@email.com"
              value={form.email} onChange={set('email')}
              autoComplete="email" inputMode="email"
            />
            {errors.email && <span className="modal-err-msg">{errors.email}</span>}
          </div>

          <div className="modal-field">
            <label className="modal-label">Data de nascimento <span className="modal-req">*</span></label>
            <input
              className={'modal-input' + (errors.nascimento ? ' modal-input--err' : '')}
              type="text" placeholder="DD/MM/AAAA"
              value={form.nascimento} onChange={set('nascimento')}
              inputMode="numeric" maxLength={10}
            />
            {errors.nascimento && <span className="modal-err-msg">{errors.nascimento}</span>}
            <span className="modal-hint">
              <i data-lucide="gift" style={{ width: 12, height: 12 }}></i>
              Se virar nosso cliente, no seu aniversário tem uma surpresa 😉
            </span>
          </div>

          <button type="submit" className="modal-btn" disabled={loading}>
            {loading ? (
              <span className="modal-spinner"></span>
            ) : (
              <>
                <i data-lucide="message-circle" style={{ width: 20, height: 20 }}></i>
                Falar no WhatsApp agora
              </>
            )}
          </button>

          <p className="modal-privacy">
            <i data-lucide="lock" style={{ width: 12, height: 12 }}></i>
            Seus dados ficam só com a 8BAC · Sem spam
          </p>

        </form>
      </div>

      <style>{`
        .modal-overlay {
          position: fixed; inset: 0; z-index: 100;
          background: rgba(10,10,11,.6);
          backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px);
          display: flex; align-items: flex-end; justify-content: center;
          padding: 0;
          animation: overlayIn .2s var(--ease-out);
        }
        @keyframes overlayIn { from { opacity: 0; } to { opacity: 1; } }

        .modal-card {
          background: #fff; width: 100%; max-width: 520px;
          border-radius: 20px 20px 0 0;
          padding: 32px 22px 36px;
          position: relative;
          animation: cardUp .3s var(--ease-out);
          max-height: 92vh; overflow-y: auto;
        }
        @keyframes cardUp {
          from { transform: translateY(40px); opacity: 0; }
          to   { transform: translateY(0);    opacity: 1; }
        }

        .modal-close {
          position: absolute; top: 16px; right: 16px;
          width: 34px; height: 34px; 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;
        }
        .modal-close:hover { background: var(--line); }

        .modal-chip {
          font-family: var(--font-mono); font-size: 11px; font-weight: 600;
          letter-spacing: 0.06em; color: var(--success);
          background: rgba(0,166,90,.08);
          padding: 6px 12px; border-radius: 999px;
          display: inline-flex; align-items: center; gap: 6px;
          margin-bottom: 16px;
        }

        .modal-title {
          font-family: var(--font-display); font-weight: 900;
          font-size: clamp(24px, 6vw, 32px); line-height: 1.08;
          letter-spacing: -0.025em; color: var(--ink-1);
          margin: 0 0 26px 0;
        }

        .modal-form { display: flex; flex-direction: column; gap: 14px; }
        .modal-row  { display: flex; flex-direction: column; gap: 14px; }

        .modal-field { display: flex; flex-direction: column; gap: 6px; }

        .modal-label {
          font-family: var(--font-sans); font-size: 13px; font-weight: 600;
          color: var(--ink-2);
        }
        .modal-req { color: var(--bac-blue); margin-left: 2px; }

        .modal-input {
          font-family: var(--font-sans); font-size: 16px;
          color: var(--ink-1); background: var(--bg-alt);
          border: 1.5px solid var(--line); border-radius: 10px;
          padding: 14px 16px; outline: none; width: 100%;
          transition: border-color .14s var(--ease-out);
          -webkit-appearance: none;
        }
        .modal-input::placeholder { color: var(--ink-4); }
        .modal-input:focus { border-color: var(--bac-blue); background: #fff; box-shadow: var(--focus-ring); }
        .modal-input--err { border-color: var(--danger); }
        .modal-input--err:focus { box-shadow: 0 0 0 3px rgba(229,56,77,.2); }

        .modal-err-msg {
          font-family: var(--font-sans); font-size: 12px; color: var(--danger);
        }

        .modal-hint {
          font-family: var(--font-sans); font-size: 12px; color: var(--ink-4);
          display: inline-flex; align-items: center; gap: 5px; margin-top: 2px;
        }

        .modal-btn {
          display: 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: 16px;
          padding: 18px; border-radius: 12px; border: 0; cursor: pointer;
          width: 100%; margin-top: 8px;
          box-shadow: 0 8px 22px rgba(0,102,254,.28);
          transition: all .14s var(--ease-out);
          -webkit-tap-highlight-color: transparent;
          min-height: 58px;
        }
        .modal-btn:hover:not(:disabled) { background: var(--bac-blue-700); transform: translateY(-1px); }
        .modal-btn:disabled { opacity: .7; cursor: not-allowed; }

        .modal-spinner {
          width: 20px; height: 20px; border-radius: 50%;
          border: 2px solid rgba(255,255,255,.3);
          border-top-color: #fff;
          animation: spin .7s linear infinite;
        }
        @keyframes spin { to { transform: rotate(360deg); } }

        .modal-privacy {
          font-family: var(--font-sans); font-size: 12px; color: var(--ink-4);
          text-align: center; margin: 4px 0 0 0;
          display: flex; align-items: center; justify-content: center; gap: 5px;
        }

        @media (min-width: 520px) {
          .modal-overlay { align-items: center; padding: 24px; }
          .modal-card { border-radius: 20px; padding: 40px 36px; }
          .modal-row { flex-direction: row; gap: 14px; }
          .modal-row .modal-field { flex: 1; }
        }
      `}</style>
    </div>
  );
}
