function ContactModal() {
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState({ nome: '', empresa: '', desejo: '' });
  const [sent, setSent] = useState(false);
  const firstRef = useRef(null);

  useEffect(() => {
    window.__openContactModal = () => { setOpen(true); setSent(false); };
  }, []);

  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    if (open) setTimeout(() => firstRef.current?.focus(), 80);
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  const close = () => setOpen(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    const msg =
      `Olá, Fidel! Tudo bem?\n\n` +
      `Meu nome é ${form.nome}.\n` +
      `Empresa / produto: ${form.empresa}.\n\n` +
      `O que desejo desenvolver:\n${form.desejo}\n\n` +
      `Aguardo seu retorno!`;
    window.open(`https://wa.me/5588997390480?text=${encodeURIComponent(msg)}`, '_blank');
    setSent(true);
  };

  if (!open) return null;

  const inputStyle = {
    background: 'var(--bg)',
    border: '1px solid var(--line)',
    borderRadius: 2,
    padding: '14px 16px',
    fontSize: 15,
    color: 'var(--fg)',
    outline: 'none',
    fontFamily: 'inherit',
    width: '100%',
    transition: 'border-color .2s',
  };

  return (
    <div
      onClick={close}
      className="modal-overlay"
      style={{
        position: 'fixed', inset: 0, zIndex: 9999,
        background: 'oklch(0 0 0 / 0.55)',
        backdropFilter: 'blur(6px)',
        WebkitBackdropFilter: 'blur(6px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20,
        animation: 'modalFadeIn .25s ease both',
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        className="modal-box"
        style={{
          background: 'var(--bg-2)',
          border: '1px solid var(--line)',
          borderRadius: 4,
          padding: 'clamp(28px, 5vw, 52px)',
          maxWidth: 520, width: '100%',
          position: 'relative',
          maxHeight: '90vh',
          overflowY: 'auto',
          animation: 'modalSlideUp .3s cubic-bezier(.2,.7,.2,1) both',
        }}
      >
        {/* Close */}
        <button onClick={close} style={{
          position: 'absolute', top: 18, right: 18,
          width: 32, height: 32, borderRadius: 999,
          border: '1px solid var(--line)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--fg-mute)', transition: 'all .2s',
        }}
          onMouseEnter={e => { e.currentTarget.style.background = 'var(--fg)'; e.currentTarget.style.color = 'var(--bg)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--fg-mute)'; }}
        >
          <svg width="11" height="11" viewBox="0 0 11 11">
            <path d="M1 1L10 10M10 1L1 10" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" />
          </svg>
        </button>

        <div className="mono" style={{ color: 'var(--accent)', marginBottom: 10, fontSize: 11, letterSpacing: '0.06em' }}>
          DIAGNÓSTICO · MÉTODO PHI Φ
        </div>
        <h3 className="serif" style={{ fontSize: 'clamp(26px, 4vw, 38px)', letterSpacing: '-0.025em', lineHeight: 1, marginBottom: 32 }}>
          {sent ? <>Mensagem <em className="italic">enviada!</em></> : <>Conta sobre o <em className="italic">seu projeto.</em></>}
        </h3>

        {sent ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <p style={{ fontSize: 16, color: 'var(--fg-dim)', lineHeight: 1.6 }}>
              Sua mensagem foi enviada pelo WhatsApp. Fidel retornará em breve para agendar os 40 minutos de diagnóstico.
            </p>
            <button onClick={close} style={{
              alignSelf: 'flex-start', padding: '14px 28px', borderRadius: 999,
              border: '1px solid var(--line)', fontSize: 14, color: 'var(--fg)',
              transition: 'all .3s',
            }}>
              Fechar
            </button>
          </div>
        ) : (
          <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <label style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              <span className="mono" style={{ fontSize: 10, color: 'var(--fg-mute)', letterSpacing: '0.1em' }}>SEU NOME</span>
              <input
                ref={firstRef}
                type="text"
                required
                placeholder="Como você se chama?"
                value={form.nome}
                onChange={e => setForm({ ...form, nome: e.target.value })}
                style={inputStyle}
                onFocus={e => e.target.style.borderColor = 'var(--accent)'}
                onBlur={e => e.target.style.borderColor = 'var(--line)'}
              />
            </label>

            <label style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              <span className="mono" style={{ fontSize: 10, color: 'var(--fg-mute)', letterSpacing: '0.1em' }}>EMPRESA / PRODUTO</span>
              <input
                type="text"
                required
                placeholder="Nome da empresa ou produto"
                value={form.empresa}
                onChange={e => setForm({ ...form, empresa: e.target.value })}
                style={inputStyle}
                onFocus={e => e.target.style.borderColor = 'var(--accent)'}
                onBlur={e => e.target.style.borderColor = 'var(--line)'}
              />
            </label>

            <label style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
              <span className="mono" style={{ fontSize: 10, color: 'var(--fg-mute)', letterSpacing: '0.1em' }}>O QUE DESEJA DESENVOLVER</span>
              <textarea
                required
                rows={3}
                placeholder="Descreva brevemente o que quer desenvolver ou resolver..."
                value={form.desejo}
                onChange={e => setForm({ ...form, desejo: e.target.value })}
                style={{ ...inputStyle, resize: 'vertical', minHeight: 90 }}
                onFocus={e => e.target.style.borderColor = 'var(--accent)'}
                onBlur={e => e.target.style.borderColor = 'var(--line)'}
              />
            </label>

            <button
              type="submit"
              style={{
                marginTop: 6,
                background: 'var(--accent)',
                color: 'var(--bg)',
                padding: '17px 28px',
                borderRadius: 999,
                fontSize: 15,
                fontWeight: 500,
                letterSpacing: '-0.01em',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12,
                transition: 'transform .3s, box-shadow .3s',
              }}
              onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 12px 40px -10px oklch(0.78 0.13 70 / 0.5)'; }}
              onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'none'; }}
            >
              Enviar pelo WhatsApp
              <svg width="17" height="17" viewBox="0 0 17 17" fill="currentColor">
                <path d="M8.5 0C3.81 0 0 3.81 0 8.5c0 1.5.39 2.9 1.07 4.12L0 17l4.5-1.18A8.47 8.47 0 0 0 8.5 17C13.19 17 17 13.19 17 8.5S13.19 0 8.5 0zm4.17 11.76c-.18.51-1.05.99-1.46 1.05-.37.06-.84.09-1.35-.09-.31-.1-.71-.24-1.22-.48-2.14-.92-3.54-3.08-3.65-3.22-.1-.15-.87-1.16-.87-2.2 0-1.05.55-1.57.75-1.78.19-.21.42-.26.56-.26h.4c.13 0 .3-.05.47.35.18.42.61 1.47.66 1.57.05.1.08.23.02.37-.06.14-.1.22-.2.34-.1.12-.2.26-.29.35-.1.1-.19.2-.08.39.11.19.48.79 1.03 1.28.71.63 1.31.82 1.5.91.19.1.3.08.41-.05.11-.14.46-.53.58-.71.13-.18.25-.15.41-.09.17.07 1.08.51 1.26.6.18.1.3.14.35.21.05.08.05.45-.13.96z" />
              </svg>
            </button>

            <p className="mono" style={{ fontSize: 11, color: 'var(--fg-mute)', textAlign: 'center', lineHeight: 1.5 }}>
              40 min · diagnóstico gratuito · sem compromisso
            </p>
          </form>
        )}
      </div>

      <style>{`
        @keyframes modalFadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes modalSlideUp { from { opacity: 0; transform: translateY(24px); } to { opacity: 1; transform: none; } }
        @media (max-width: 480px) {
          .modal-box { padding: 28px 20px !important; border-radius: 2px !important; }
          .modal-overlay { padding: 12px !important; align-items: flex-end !important; }
          .modal-box { border-radius: 8px 8px 2px 2px !important; }
        }
      `}</style>
    </div>
  );
}

window.ContactModal = ContactModal;
window.__openContactModal = () => {};
