/* WhatsApp modal — abre quando qualquer botão "Falar no WhatsApp" é clicado */

function WhatsModal({ open, onClose }) {
  const [nome, setNome] = React.useState('');
  const [fone, setFone] = React.useState('');
  const [sent, setSent] = React.useState(false);
  const [errors, setErrors] = React.useState({ nome: '', fone: '' });

  React.useEffect(() => {
    if (!open) { setSent(false); setErrors({ nome: '', fone: '' }); return; }
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  const formatPhone = (v) => {
    const d = v.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 <= 10) return `(${d.slice(0,2)}) ${d.slice(2,6)}-${d.slice(6)}`;
    return `(${d.slice(0,2)}) ${d.slice(2,7)}-${d.slice(7)}`;
  };

  const submit = (e) => {
    e.preventDefault();
    const next = { nome: '', fone: '' };
    if (!nome.trim()) next.nome = 'Por favor, informe seu nome.';
    if (fone.replace(/\D/g,'').length < 10) next.fone = 'Informe um telefone válido com DDD.';
    if (next.nome || next.fone) { setErrors(next); return; }
    setErrors({ nome: '', fone: '' });
    const msg = `Olá! Meu nome é ${nome.trim()} e gostaria de saber mais sobre a Amparus. Meu telefone: ${fone}.`;
    const url = `https://wa.me/554797321834?text=${encodeURIComponent(msg)}`;
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({ event: 'whatsapp_lead', nome: nome.trim() });
    window.ampTrack && window.ampTrack('whatsapp-submit');
    const _sid = sessionStorage.getItem('_amp_sid') || '';
    fetch('/track/lead', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ sessionId: _sid, nome: nome.trim(), fone: fone }),
    }).catch(function(){});
    setSent(true);
    const dest = `/obrigado.html?url=${encodeURIComponent(url)}&nome=${encodeURIComponent(nome.trim())}`;
    setTimeout(() => { window.location.href = dest; }, 200);
  };

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 9999,
        background: 'rgba(31,55,68,0.55)',
        backdropFilter: 'blur(8px)',
        display: 'grid', placeItems: 'center',
        padding: 20,
        animation: 'whats-fade 0.2s ease',
      }}
    >
      <style>{`
        @keyframes whats-fade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes whats-rise { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
        .whats-input {
          width: 100%;
          padding: 14px 16px;
          font-size: 16px;
          font-family: inherit;
          background: #fbf8f3;
          border: 1px solid #e3d9c9;
          border-radius: 6px;
          color: #1f2b33;
          outline: none;
          transition: border-color 0.15s;
        }
        .whats-input:focus { border-color: #2d4a5a; }
      `}</style>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: '100%',
          maxWidth: 440,
          background: '#f7f3ee',
          borderRadius: 10,
          overflow: 'hidden',
          boxShadow: '0 24px 64px -16px rgba(0,0,0,0.35)',
          animation: 'whats-rise 0.25s ease',
          fontFamily: '"Plus Jakarta Sans", system-ui, sans-serif',
        }}
      >
        {!sent ? (
          <>
            <div style={{ padding: '24px 28px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 40, height: 40, borderRadius: 999, background: '#25612e', color: '#f4ede1', display: 'grid', placeItems: 'center' }}>
                  <WhatsIcon size={20} />
                </div>
                <div>
                  <div style={{ fontSize: 16, fontWeight: 600, color: '#1f2b33', letterSpacing: '-0.01em' }}>Conversar pelo WhatsApp</div>
                  <div style={{ fontSize: 12, color: '#6f7a82', marginTop: 2 }}>Respondemos das 8h às 18h</div>
                </div>
              </div>
              <button onClick={onClose} style={{ width: 32, height: 32, borderRadius: 999, color: '#6f7a82', display: 'grid', placeItems: 'center' }}>
                <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
              </button>
            </div>

            <form onSubmit={submit} style={{ padding: '20px 28px 28px' }}>
              <p style={{ fontSize: 14, color: '#3a4853', lineHeight: 1.55, marginBottom: 22 }}>
                Deixe seu nome e telefone — a coordenação vai abrir uma conversa pessoal com você, sem mensagens automáticas.
              </p>

              <label style={{ display: 'block', marginBottom: 14 }}>
                <span style={{ display: 'block', fontSize: 12, fontWeight: 600, color: '#3a4853', letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 6 }}>Seu nome</span>
                <input
                  className="whats-input"
                  value={nome}
                  onChange={(e) => { setNome(e.target.value); if (errors.nome) setErrors((p) => ({ ...p, nome: '' })); }}
                  placeholder="Como podemos chamá-lo"
                  autoFocus
                  style={errors.nome ? { borderColor: '#c0392b' } : null}
                  aria-invalid={errors.nome ? 'true' : 'false'}
                />
                {errors.nome && <span style={{ display: 'block', fontSize: 12, color: '#c0392b', marginTop: 6 }}>{errors.nome}</span>}
              </label>

              <label style={{ display: 'block', marginBottom: 22 }}>
                <span style={{ display: 'block', fontSize: 12, fontWeight: 600, color: '#3a4853', letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 6 }}>Telefone com DDD</span>
                <input
                  className="whats-input"
                  value={fone}
                  onChange={(e) => { setFone(formatPhone(e.target.value)); if (errors.fone) setErrors((p) => ({ ...p, fone: '' })); }}
                  placeholder="(47) 9 0000-0000"
                  inputMode="tel"
                  style={errors.fone ? { borderColor: '#c0392b' } : null}
                  aria-invalid={errors.fone ? 'true' : 'false'}
                />
                {errors.fone && <span style={{ display: 'block', fontSize: 12, color: '#c0392b', marginTop: 6 }}>{errors.fone}</span>}
              </label>

              <button
                type="submit"
                style={{
                  width: '100%',
                  padding: '14px 22px',
                  background: '#25612e',
                  color: '#fbf8f3',
                  border: 0,
                  borderRadius: 999,
                  fontFamily: 'inherit',
                  fontSize: 15,
                  fontWeight: 600,
                  cursor: 'pointer',
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: 10,
                  transition: 'background 0.2s',
                }}
              >
                <WhatsIcon size={16} />
                Abrir conversa no WhatsApp
              </button>

              <p style={{ fontSize: 11, color: '#6f7a82', marginTop: 14, textAlign: 'center', lineHeight: 1.5 }}>
                Ao enviar, você concorda em ser contatado pela equipe da Amparus.
              </p>
            </form>
          </>
        ) : (
          <div style={{ padding: '40px 28px', textAlign: 'center' }}>
            <div style={{ width: 56, height: 56, borderRadius: 999, background: '#25612e', color: '#f4ede1', display: 'grid', placeItems: 'center', margin: '0 auto 18px' }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M5 12.5l4.5 4.5L19 7.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </div>
            <div style={{ fontSize: 18, fontWeight: 500, color: '#1f2b33', letterSpacing: '-0.01em' }}>Tudo certo, {nome.split(' ')[0]}.</div>
            <p style={{ fontSize: 14, color: '#3a4853', marginTop: 10, lineHeight: 1.55 }}>
              Abrindo o WhatsApp em uma nova aba. Se nada aparecer, libere o pop-up do navegador.
            </p>
            <button onClick={onClose} style={{ marginTop: 22, padding: '10px 20px', borderRadius: 999, background: 'transparent', border: '1px solid #e3d9c9', color: '#1f2b33', fontSize: 14, fontWeight: 500 }}>
              Fechar
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

// Global helper: any button can call window.openWhatsForm()
function WhatsModalHost() {
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    window.openWhatsForm = () => setOpen(true);
    return () => { delete window.openWhatsForm; };
  }, []);
  return <WhatsModal open={open} onClose={() => setOpen(false)} />;
}

Object.assign(window, { WhatsModal, WhatsModalHost });
