// ContatoForm.jsx — shared contact form components.
// Loaded by index.html (Contact section) and contato.html (standalone page).
//
// Form submission: uses Formspree (formspree.io — free tier, 50 submissions/month).
// Replace FORMSPREE_FORM_ID below with the ID from your Formspree dashboard.
const FORMSPREE_FORM_ID = "YOUR_FORMSPREE_FORM_ID"; // ← replace with your ID from formspree.io/dashboard

const CONTACT_TIPOS = [
  { id: "escola",   label: "Escola",           color: [45,  111, 247], desc: "Solicitar visita ou kit experimental" },
  { id: "apoiar",   label: "Apoiar",            color: [255, 179, 71],  desc: "Doação ou suporte financeiro"         },
  { id: "parceria", label: "Parceria",          color: [107, 63,  255], desc: "Escola, empresa, fundação ou órgão público" },
  { id: "outro",    label: "Imprensa / Outros", color: [0,   229, 255], desc: "Jornalistas, pesquisadores, curiosos"  },
];

function ContactTabs({ tipo, setTipo, isMobile }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: isMobile ? "repeat(2, 1fr)" : "repeat(4, 1fr)",
      gap: 10, marginBottom: 36,
    }}>
      {CONTACT_TIPOS.map(t => {
        const [r, g, b] = t.color;
        const active = tipo === t.id;
        return (
          <button key={t.id} onClick={() => setTipo(t.id)} style={{
            padding: "16px 18px",
            background: active ? `rgba(${r},${g},${b},0.08)` : "var(--deep)",
            border: `1px solid ${active ? `rgba(${r},${g},${b},0.50)` : "var(--line)"}`,
            borderRadius: "var(--r-lg)", cursor: "pointer", textAlign: "left",
            transition: "all 0.22s var(--ease-out)",
            boxShadow: active ? `0 0 28px rgba(${r},${g},${b},0.12)` : "none",
            position: "relative", overflow: "hidden",
          }}>
            <div style={{
              position: "absolute", top: 0, left: 12, right: 12, height: 1,
              background: `linear-gradient(90deg, transparent, rgba(${r},${g},${b},${active ? 0.55 : 0.15}), transparent)`,
            }} />
            <div style={{
              fontFamily: "var(--font-display)", fontSize: 14, fontWeight: 500,
              color: active ? `rgb(${r},${g},${b})` : "var(--fg-2)",
              marginBottom: 4, transition: "color 0.22s",
            }}>{t.label}</div>
            <div style={{
              fontFamily: "var(--font-mono)", fontSize: 9,
              color: "var(--fg-4)", letterSpacing: "0.08em", lineHeight: 1.4,
            }}>{t.desc}</div>
          </button>
        );
      })}
    </div>
  );
}

function ContatoFormPanel({ tipo, isMobile }) {
  const tipoAtual = CONTACT_TIPOS.find(t => t.id === tipo);
  const [r, g, b] = tipoAtual.color;
  const formRef = React.useRef(null);
  const [status, setStatus] = React.useState("idle"); // idle | loading | success | error
  const [errorMsg, setErrorMsg] = React.useState("");

  // Reset to idle when contact type changes
  React.useEffect(() => { setStatus("idle"); setErrorMsg(""); }, [tipo]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    const form = formRef.current;

    // Basic required-field validation
    const nome = form.querySelector("[name=nome]");
    const email = form.querySelector("[name=email]");
    if (!nome || !nome.value.trim()) { nome && nome.focus(); return; }
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value)) {
      email && email.focus(); return;
    }

    setStatus("loading");
    const data = Object.fromEntries(new FormData(form));
    data._tipo = tipoAtual.label;

    if (FORMSPREE_FORM_ID === "YOUR_FORMSPREE_FORM_ID") {
      // Fallback: open mail client when Formspree is not yet configured
      const subject = encodeURIComponent(`[${tipoAtual.label}] ${data.nome || ""}`);
      const body = encodeURIComponent(Object.entries(data).map(([k,v]) => `${k}: ${v}`).join("\n"));
      window.location.href = `mailto:fisicaalemdopapel@gmail.com?subject=${subject}&body=${body}`;
      setStatus("idle");
      return;
    }

    try {
      const res = await fetch(`https://formspree.io/f/${FORMSPREE_FORM_ID}`, {
        method: "POST",
        headers: { "Accept": "application/json", "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (res.ok) {
        setStatus("success");
        form.reset();
      } else {
        const json = await res.json().catch(() => ({}));
        setErrorMsg(json.error || "Ocorreu um erro. Tente novamente.");
        setStatus("error");
      }
    } catch {
      setErrorMsg("Sem conexão. Verifique sua internet e tente novamente.");
      setStatus("error");
    }
  };

  if (status === "success") {
    return (
      <div style={{
        background: "var(--deep)", border: "1px solid rgba(46,230,168,0.35)",
        borderRadius: "var(--r-lg)", padding: isMobile ? "40px 24px" : "56px 40px",
        textAlign: "center",
      }}>
        <div style={{ fontSize: 40, marginBottom: 16 }}>✓</div>
        <div style={{
          fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 600,
          color: "var(--success)", marginBottom: 12,
        }}>Mensagem enviada!</div>
        <p style={{ fontSize: 15, color: "var(--fg-2)", lineHeight: 1.6, margin: "0 0 28px" }}>
          Recebemos seu contato. Respondemos em até 48 horas úteis.
        </p>
        <button onClick={() => setStatus("idle")}
          style={{
            fontFamily: "var(--font-body)", fontSize: 13, color: "var(--fg-3)",
            background: "transparent", border: "1px solid var(--line)",
            borderRadius: "var(--r-md)", padding: "8px 20px", cursor: "pointer",
          }}>Enviar outra mensagem</button>
      </div>
    );
  }

  return (
    <form ref={formRef} style={{
      background: "var(--deep)", border: "1px solid var(--line)",
      borderRadius: "var(--r-lg)", padding: isMobile ? "24px 20px" : "32px 28px",
      boxShadow: "0 1px 0 rgba(255,255,255,0.05) inset, 0 24px 60px rgba(0,0,0,0.35)",
      position: "relative", overflow: "hidden",
    }} onSubmit={handleSubmit} noValidate>
      <div style={{
        position: "absolute", top: 0, left: 28, right: 28, height: 1,
        background: `linear-gradient(90deg, transparent, rgba(${r},${g},${b},0.80) 50%, transparent)`,
      }} />

      <div style={{
        fontFamily: "var(--font-mono)", fontSize: 10,
        color: `rgba(${r},${g},${b},0.9)`, letterSpacing: "0.22em",
        textTransform: "uppercase", marginBottom: 20,
      }}>{tipoAtual.label}</div>

      <CField name="nome" label="Nome" placeholder={tipo === "parceria" ? "Nome / Organização" : "Seu nome"} required r={r} g={g} b={b} />
      <CField name="email" label="E-mail" placeholder="seu@email.com" type="email" required r={r} g={g} b={b} />

      {tipo === "escola" && <>
        <CField name="escola" label="Escola / Instituição" placeholder="Nome da escola" r={r} g={g} b={b} />
        <CField name="cidade" label="Cidade, Estado" placeholder="Ex: Goiânia, GO" r={r} g={g} b={b} />
        <CSelect name="assunto" label="Assunto" options={["Solicitar visita presencial","Solicitar kit experimental","Visita + kit","Dúvida sobre o programa"]} r={r} g={g} b={b} />
        <CSelect name="nivel" label="Nível de ensino" options={["Ensino Fundamental II","Ensino Médio","Superior","Outro"]} r={r} g={g} b={b} />
        <CTextarea name="mensagem" label="Mensagem" placeholder="Contexto adicional (opcional)" rows={3} r={r} g={g} b={b} />
      </>}

      {tipo === "apoiar" && <>
        <CSelect name="assunto" label="Assunto" options={["Doação pontual","Contribuição mensal","Parceria de longo prazo","Outro"]} r={r} g={g} b={b} />
        <CTextarea name="mensagem" label="Mensagem" placeholder="Conte como imagina esse apoio" rows={4} r={r} g={g} b={b} />
      </>}

      {tipo === "parceria" && <>
        <CSelect name="assunto" label="Assunto" options={["Extensão / pesquisa universitária","Patrocínio empresarial","Copatrocínio — Fundação / ONG","Parceria com poder público","Outro"]} r={r} g={g} b={b} />
        <CField name="cidade" label="Cidade, Estado" placeholder="Ex: Goiânia, GO" r={r} g={g} b={b} />
        <CTextarea name="proposta" label="Proposta / contexto" placeholder="Como você imagina essa parceria?" rows={4} r={r} g={g} b={b} />
      </>}

      {tipo === "outro" && <>
        <CField name="veiculo" label="Veículo / Instituição" placeholder="Jornal, universidade, etc. (opcional)" r={r} g={g} b={b} />
        <CSelect name="assunto" label="Assunto" options={["Imprensa / Cobertura","Pesquisa acadêmica","Curiosidade geral","Outro"]} r={r} g={g} b={b} />
        <CTextarea name="mensagem" label="Mensagem" placeholder="Qual é o assunto?" rows={4} r={r} g={g} b={b} />
      </>}

      {status === "error" && (
        <div style={{
          marginBottom: 16, padding: "12px 14px",
          background: "rgba(255,77,109,0.1)", border: "1px solid rgba(255,77,109,0.35)",
          borderRadius: "var(--r-sm)", fontSize: 13, color: "var(--danger)", lineHeight: 1.5,
        }}>{errorMsg}</div>
      )}

      <button type="submit" disabled={status === "loading"} style={{
        width: "100%", padding: "15px 24px",
        background: status === "loading" ? "rgba(255,255,255,0.08)" : `rgb(${r},${g},${b})`,
        border: "none", borderRadius: "var(--r-md)",
        fontFamily: "var(--font-display)", fontSize: 14, fontWeight: 500,
        color: (status === "loading") ? "var(--fg-3)" : (tipo === "apoiar" ? "#000" : "#fff"),
        cursor: status === "loading" ? "not-allowed" : "pointer",
        display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
        boxShadow: status === "loading" ? "none" : `0 0 28px rgba(${r},${g},${b},0.35)`,
        transition: "all 0.2s",
      }}>
        {status === "loading" ? "Enviando…" : (<>Enviar <span>→</span></>)}
      </button>
      <div style={{
        marginTop: 12, textAlign: "center",
        fontFamily: "var(--font-body)", fontSize: 12,
        color: "var(--fg-4)",
      }}>Respondemos em até 48 horas úteis</div>
    </form>
  );
}

function CField({ name, label, placeholder, type = "text", required, r, g, b }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <label htmlFor={`cf-${name}`} style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-3)", letterSpacing: "0.22em", textTransform: "uppercase", marginBottom: 7, display: "block" }}>{label}{required && <span style={{ color: "var(--danger)", marginLeft: 3 }}>*</span>}</label>
      <input id={`cf-${name}`} name={name} type={type} placeholder={placeholder} required={required}
        autoComplete={type === "email" ? "email" : name === "nome" ? "name" : "off"}
        style={{
          width: "100%", padding: "11px 13px",
          fontFamily: "var(--font-body)", fontSize: 14,
          color: "var(--fg-1)", background: "var(--void)",
          border: "1px solid var(--line-strong)", borderRadius: "var(--r-md)",
          outline: "none", boxSizing: "border-box", transition: "border-color 0.2s, box-shadow 0.2s",
        }}
        onFocus={(e) => { e.target.style.borderColor = `rgba(${r},${g},${b},0.7)`; e.target.style.boxShadow = `0 0 0 3px rgba(${r},${g},${b},0.15)`; }}
        onBlur={(e) => { e.target.style.borderColor = "var(--line-strong)"; e.target.style.boxShadow = "none"; }}
      />
    </div>
  );
}

function CSelect({ name, label, options, r, g, b }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <label htmlFor={`cf-${name}`} style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-3)", letterSpacing: "0.22em", textTransform: "uppercase", marginBottom: 7, display: "block" }}>{label}</label>
      <select id={`cf-${name}`} name={name} style={{
        width: "100%", padding: "11px 13px",
        fontFamily: "var(--font-body)", fontSize: 14,
        color: "var(--fg-1)", background: "var(--void)",
        border: "1px solid var(--line-strong)", borderRadius: "var(--r-md)",
        outline: "none", appearance: "none", boxSizing: "border-box",
        cursor: "pointer", transition: "border-color 0.2s, box-shadow 0.2s",
      }}
        onFocus={(e) => { e.target.style.borderColor = `rgba(${r},${g},${b},0.7)`; e.target.style.boxShadow = `0 0 0 3px rgba(${r},${g},${b},0.15)`; }}
        onBlur={(e) => { e.target.style.borderColor = "var(--line-strong)"; e.target.style.boxShadow = "none"; }}>
        {options.map(o => <option key={o} value={o} style={{ background: "var(--void)" }}>{o}</option>)}
      </select>
    </div>
  );
}

function CTextarea({ name, label, placeholder, rows, r, g, b }) {
  return (
    <div style={{ marginBottom: 22 }}>
      <label htmlFor={`cf-${name}`} style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-3)", letterSpacing: "0.22em", textTransform: "uppercase", marginBottom: 7, display: "block" }}>{label}</label>
      <textarea id={`cf-${name}`} name={name} rows={rows} placeholder={placeholder} style={{
        width: "100%", padding: "12px 14px",
        fontFamily: "var(--font-body)", fontSize: 14,
        color: "var(--fg-1)", background: "var(--void)",
        border: "1px solid var(--line-strong)", borderRadius: "var(--r-md)",
        resize: "vertical", outline: "none", boxSizing: "border-box",
        transition: "border-color 0.2s, box-shadow 0.2s",
      }}
        onFocus={(e) => { e.target.style.borderColor = `rgba(${r},${g},${b},0.7)`; e.target.style.boxShadow = `0 0 0 3px rgba(${r},${g},${b},0.15)`; }}
        onBlur={(e) => { e.target.style.borderColor = "var(--line-strong)"; e.target.style.boxShadow = "none"; }}
      />
    </div>
  );
}
