function ContactModal() {
  const [open, setOpen] = React.useState(false);
  const [form, setForm] = React.useState({ nome: '', email: '', celular: '', mensagem: '' });
  const [sent, setSent] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');

  React.useEffect(() => {
    window.openContactModal = () => { setOpen(true); setSent(false); };
    return () => { delete window.openContactModal; };
  }, []);

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

  const set = (field) => (e) => setForm(f => ({ ...f, [field]: e.target.value }));

  const formatPhone = (val) => {
    const n = val.replace(/\D/g, '').slice(0, 11);
    if (n.length <= 2) return n;
    if (n.length <= 7) return `(${n.slice(0,2)}) ${n.slice(2)}`;
    return `(${n.slice(0,2)}) ${n.slice(2,7)}-${n.slice(7)}`;
  };

  const handlePhone = (e) => setForm(f => ({ ...f, celular: formatPhone(e.target.value) }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok || !data.ok) throw new Error(data.error || 'Erro desconhecido');
      setSent(true);
      setForm({ nome: '', email: '', celular: '', mensagem: '' });
    } catch (err) {
      setError('Não conseguimos enviar sua mensagem. Tente novamente ou escreva diretamente para contact@roqish.com');
    } finally {
      setLoading(false);
    }
  };

  if (!open) return null;

  return (
    <div
      onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(26, 22, 20, 0.55)',
        backdropFilter: 'blur(4px)',
        WebkitBackdropFilter: 'blur(4px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '20px',
      }}
    >
      <div style={{
        background: 'var(--bg-elevated)',
        borderRadius: 'var(--radius-2xl)',
        padding: '40px',
        width: '100%',
        maxWidth: 480,
        boxShadow: 'var(--shadow-xl)',
        position: 'relative',
      }}>
        <button
          onClick={() => setOpen(false)}
          aria-label="Fechar"
          style={{
            position: 'absolute', top: 16, right: 16,
            width: 32, height: 32, borderRadius: 8,
            background: 'var(--bg-soft)', border: '1px solid var(--line)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', color: 'var(--ink-3)',
          }}
        >
          <Icon.X />
        </button>

        {sent ? (
          <div style={{ textAlign: 'center', padding: '24px 0' }}>
            <div style={{
              width: 56, height: 56, borderRadius: '50%',
              background: 'var(--green-tint)', border: '1px solid var(--green-soft)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              margin: '0 auto 20px',
            }}>
              <Icon.Check size={24} color="var(--green-deep)" />
            </div>
            <h3 style={{ fontSize: 20, fontWeight: 700, color: 'var(--ink)', marginBottom: 8 }}>
              Mensagem enviada!
            </h3>
            <p style={{ fontSize: 15, color: 'var(--ink-3)', lineHeight: 1.6, marginBottom: 24 }}>
              Recebemos sua mensagem e responderemos o mais breve possível.
            </p>
            <button onClick={() => setOpen(false)} className="btn btn-primary" style={{ width: '100%' }}>
              Fechar
            </button>
          </div>
        ) : (
          <>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 28 }}>
              <img
                src="/uploads/porquinho-headset.png"
                alt="Porquinho com headset"
                style={{ width: 96, height: 96, objectFit: 'contain', flexShrink: 0 }}
              />
              <div>
                <h2 style={{ fontSize: 22, fontWeight: 800, color: 'var(--ink)', marginBottom: 6 }}>
                  Fale com a gente
                </h2>
                <p style={{ fontSize: 15, color: 'var(--ink-3)', lineHeight: 1.55 }}>
                  Dúvidas ou sugestões? Adoramos ouvir quem usa o Econome. Responderemos o mais breve possível.
                </p>
              </div>
            </div>

            <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div>
                <label style={labelStyle}>Nome</label>
                <input
                  type="text" required value={form.nome}
                  onChange={set('nome')} placeholder="Seu nome"
                  style={inputStyle}
                />
              </div>
              <div>
                <label style={labelStyle}>E-mail</label>
                <input
                  type="email" required value={form.email}
                  onChange={set('email')} placeholder="seu@email.com"
                  style={inputStyle}
                />
              </div>
              <div>
                <label style={labelStyle}>Celular <span style={{ color: 'var(--ink-4)', fontWeight: 400 }}>(opcional)</span></label>
                <input
                  type="tel" value={form.celular}
                  onChange={handlePhone} placeholder="(00) 00000-0000"
                  style={inputStyle}
                />
              </div>
              <div>
                <label style={labelStyle}>Mensagem</label>
                <textarea
                  required value={form.mensagem}
                  onChange={set('mensagem')} placeholder="Conta pra gente..."
                  rows={4}
                  style={{ ...inputStyle, resize: 'vertical', minHeight: 100 }}
                />
              </div>
              {error && (
                <p style={{ fontSize: 13.5, color: 'var(--red)', lineHeight: 1.5, marginTop: -4 }}>
                  {error}
                </p>
              )}
              <button type="submit" disabled={loading} className="btn btn-primary" style={{ marginTop: 4, opacity: loading ? 0.7 : 1 }}>
                {loading ? 'Enviando…' : 'Enviar mensagem'}
              </button>
            </form>
          </>
        )}
      </div>

      <style>{`
        .contact-input:focus {
          outline: none;
          border-color: var(--purple) !important;
          box-shadow: 0 0 0 3px var(--purple-tint);
        }
      `}</style>
    </div>
  );
}

const labelStyle = {
  display: 'block',
  fontSize: 13,
  fontWeight: 600,
  color: 'var(--ink-2)',
  marginBottom: 6,
};

const inputStyle = {
  width: '100%',
  padding: '10px 14px',
  fontSize: 15,
  color: 'var(--ink)',
  background: 'var(--bg)',
  border: '1px solid var(--line)',
  borderRadius: 'var(--radius-md)',
  fontFamily: 'inherit',
  transition: 'border-color 0.15s, box-shadow 0.15s',
  outline: 'none',
};

window.ContactModal = ContactModal;
