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

  // Bloqueia scroll do body enquanto modal aberto
  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  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 validate() {
    const e = {};
    if (!form.nome.trim() || form.nome.trim().length < 2) e.nome = 'Informe seu nome completo.';
    const digits = form.whatsapp.replace(/\D/g, '');
    if (digits.length < 10) e.whatsapp = 'WhatsApp inválido.';
    if (form.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'E-mail inválido.';
    return e;
  }

  async function handleSubmit(e) {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length) { setErrors(errs); return; }
    setLoading(true);
    await onSubmit(form);
    window.open(whatsappLink, '_blank');
    onClose();
  }

  function set(field) {
    return (e) => {
      const val = field === 'whatsapp' ? maskPhone(e.target.value) : e.target.value;
      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-logo">
          <span style={{ color: 'var(--bac-blue)' }}>8</span>
          <span style={{ color: 'var(--bac-navy)' }}>BAC</span>
        </div>

        <h2 className="modal-title">Antes de ir pro WhatsApp</h2>
        <p className="modal-sub">
          Me conta rapidinho sobre você — assim eu já chego no diagnóstico preparado pra te ajudar de verdade.
        </p>

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

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

          <div className="modal-field">
            <label className="modal-label">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">
              E-mail <span className="modal-optional">opcional</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>

          <button type="submit" className="modal-btn" disabled={loading}>
            {loading ? (
              <span className="modal-spinner"></span>
            ) : (
              <>
                <i data-lucide="message-circle" style={{ width: 18, height: 18 }}></i>
                Quero meu diagnóstico gratuito
              </>
            )}
          </button>

          <p className="modal-privacy">
            <i data-lucide="lock" style={{ width: 12, height: 12 }}></i>
            Seus dados são usados só para o diagnóstico. 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: 480px;
          border-radius: 20px 20px 0 0;
          padding: 32px 24px 40px;
          position: relative;
          animation: cardUp .28s 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: 32px; height: 32px; 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-logo {
          font-family: var(--font-display); font-weight: 900;
          font-size: 22px; letter-spacing: -0.04em; line-height: 1;
          margin-bottom: 20px;
        }
        .modal-title {
          font-family: var(--font-display); font-weight: 900;
          font-size: clamp(22px, 5vw, 28px); line-height: 1.1;
          letter-spacing: -0.02em; color: var(--ink-1); margin: 0 0 10px 0;
        }
        .modal-sub {
          font-family: var(--font-sans); font-size: 15px; line-height: 1.55;
          color: var(--ink-3); margin: 0 0 24px 0;
        }

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

        .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); display: flex; align-items: center; gap: 4px;
        }
        .modal-req { color: var(--bac-blue); }
        .modal-optional {
          font-family: var(--font-mono); font-size: 10px; font-weight: 600;
          color: var(--ink-4); text-transform: uppercase; letter-spacing: 0.06em;
          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-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: 4px;
          transition: background .14s var(--ease-out);
          -webkit-tap-highlight-color: transparent;
          min-height: 56px;
        }
        .modal-btn:hover:not(:disabled) { background: var(--bac-blue-700); }
        .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: 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; }
        }
      `}</style>
    </div>
  );
}
