const Contact = () => {
  const services = ["Site", "Software", "SaaS", "WhatsApp", "E-commerce", "Branding", "Social"];

  const [picked, setPicked]     = React.useState(["Site"]);
  const [status, setStatus]     = React.useState("idle"); // idle | loading | success | error
  const [errorMsg, setErrorMsg] = React.useState("");

  const toggle = (s) => setPicked(p => p.includes(s) ? p.filter(x => x !== s) : [...p, s]);

  const onSubmit = async (e) => {
    e.preventDefault();
    setStatus("loading");
    setErrorMsg("");

    const fd = new FormData(e.target);
    const body = {
      name:     fd.get("name"),
      email:    fd.get("email"),
      company:  fd.get("company"),
      services: picked,
      budget:   fd.get("budget"),
      message:  fd.get("message"),
    };

    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });

      if (res.ok) {
        setStatus("success");
        e.target.reset();
        setPicked(["Site"]);
      } else {
        const data = await res.json().catch(() => ({}));
        setErrorMsg(data.error || "Algo deu errado. Tente novamente.");
        setStatus("error");
      }
    } catch {
      setErrorMsg("Sem conexão. Tente novamente.");
      setStatus("error");
    }
  };

  return (
    <section className="section" id="contact">
      <div className="container">
        <div className="contact">
          <div className="contact-grid">
            <div>
              <div className="eyebrow">Vamos conversar · 09</div>
              <h2 style={{marginTop:20}}>Conta o que<br/>você tem em<br/>mente. <em>A gente<br/>responde.</em></h2>
              <p className="sub">Primeira conversa é sempre de graça e sem compromisso. Em 30 minutos saímos com um diagnóstico e um caminho claro — mesmo que a gente não seja o parceiro certo pra você.</p>
              <div className="contact-info">
                <div className="it"><span className="lb">E-mail</span>contato@bboxdigital.com.br</div>
                <div className="it"><span className="lb">WhatsApp</span>+55 11 98741-1333</div>
                <div className="it"><span className="lb">Studio</span>São Paulo · Remoto BR</div>
                <div className="it"><span className="lb">Horário</span>Seg–Sex · 9h–18h</div>
              </div>
            </div>

            {status === "success" ? (
              <div className="form" style={{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",textAlign:"center",gap:16,minHeight:320}}>
                <svg width="48" height="48" viewBox="0 0 48 48" fill="none">
                  <circle cx="24" cy="24" r="24" fill="#4ACCC0" fillOpacity="0.12"/>
                  <path d="M14 24l8 8 12-14" stroke="#4ACCC0" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
                <h3 style={{margin:0}}>Mensagem enviada!</h3>
                <p className="sub" style={{margin:0}}>Recebemos seu contato e retornamos em até 1 dia útil.</p>
                <button className="btn-primary" onClick={() => setStatus("idle")}>Enviar outro</button>
              </div>
            ) : (
              <form className="form" onSubmit={onSubmit}>
                <div className="field">
                  <label>Nome</label>
                  <input name="name" required placeholder="Seu nome completo"/>
                </div>
                <div className="field">
                  <label>E-mail de trabalho</label>
                  <input name="email" type="email" required placeholder="voce@empresa.com.br"/>
                </div>
                <div className="field">
                  <label>Empresa</label>
                  <input name="company" placeholder="Nome da empresa"/>
                </div>
                <div className="field">
                  <label>O que você precisa</label>
                  <div className="chips">
                    {services.map(s => (
                      <span key={s} className={`chip ${picked.includes(s) ? "active" : ""}`} onClick={() => toggle(s)}>{s}</span>
                    ))}
                  </div>
                </div>
                <div className="field">
                  <label>Orçamento estimado</label>
                  <select name="budget">
                    <option>Ainda não sei</option>
                    <option>Até R$ 3 mil</option>
                    <option>R$ 3 – 5 mil</option>
                    <option>R$ 5 – 15 mil</option>
                    <option>Acima de R$ 15 mil</option>
                  </select>
                </div>
                <div className="field">
                  <label>Mensagem</label>
                  <textarea name="message" rows={3} required placeholder="Conte brevemente o projeto…"/>
                </div>

                {status === "error" && (
                  <p style={{color:"#e53e3e",fontSize:14,margin:"0 0 8px"}}>{errorMsg}</p>
                )}

                <button type="submit" className="btn-primary submit" disabled={status === "loading"}>
                  {status === "loading" ? "Enviando…" : "Enviar mensagem"}
                  {status !== "loading" && (
                    <svg width="14" height="14" viewBox="0 0 12 12" fill="none">
                      <path d="M3 9L9 3M9 3H4M9 3V8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                    </svg>
                  )}
                </button>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
};
window.Contact = Contact;
