// ContatoPage.jsx — dedicated contact experience.
// Hero: ConnectionNetwork — nodes drift slowly and form glowing edges when close.
// Thematically: connections, communication, reaching out.

function ConnectionNetwork() {
  const ref = React.useRef(null);

  React.useEffect(() => {
    const canvas = ref.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    const dpr = Math.min(window.devicePixelRatio || 1, 1.5);
    let w = 0, h = 0, raf = null;
    let paused = document.hidden;
    let offscreen = false;
    let prevTime = null;

    const N_NODES = 18; // slightly reduced — still dense, meaningfully less work
    let nodes = [];

    function initNodes() {
      nodes = Array.from({ length: N_NODES }, () => ({
        x:  Math.random() * w,
        y:  Math.random() * h,
        vx: (Math.random() - 0.5) * 0.22,
        vy: (Math.random() - 0.5) * 0.22,
        r:  2.2 + Math.random() * 1.8,
        // Each node slowly pulses
        pulseOffset: Math.random() * Math.PI * 2,
        pulseSpeed:  0.0008 + Math.random() * 0.0006,
      }));
    }

    function resize() {
      const rect = canvas.getBoundingClientRect();
      w = rect.width; h = rect.height;
      canvas.width  = w * dpr;
      canvas.height = h * dpr;
      ctx.scale(dpr, dpr);
      initNodes();
    }
    resize();
    const ro = new ResizeObserver(resize);
    ro.observe(canvas);

    function checkPaused() {
      const should = document.hidden || offscreen;
      if (!paused && should) paused = true;
      else if (paused && !should) { paused = false; if (!raf) tick(0); }
    }
    document.addEventListener("visibilitychange", checkPaused);

    const visObs = new IntersectionObserver(
      ([e]) => { offscreen = !e.isIntersecting; checkPaused(); },
      { threshold: 0.01 }
    );
    visObs.observe(canvas);

    // Connection threshold: nodes within this distance get linked
    // Dynamic: slightly breathes to avoid static-looking layout
    const BASE_DIST = () => Math.min(w, h) * 0.28;

    function tick(now) {
      if (paused) { raf = null; return; }
      const dt = prevTime !== null ? Math.min(now - prevTime, 32) : 16;
      prevTime = now;

      // Move nodes — soft boundary reflection
      nodes.forEach(n => {
        n.x += n.vx * dt * 0.5;
        n.y += n.vy * dt * 0.5;
        // Soft bounce off edges
        const margin = 30;
        if (n.x < margin)     { n.vx += 0.008; }
        if (n.x > w - margin) { n.vx -= 0.008; }
        if (n.y < margin)     { n.vy += 0.008; }
        if (n.y > h - margin) { n.vy -= 0.008; }
        // Very mild drag
        n.vx *= 0.9995;
        n.vy *= 0.9995;
      });

      ctx.clearRect(0, 0, w, h);
      ctx.fillStyle = "rgba(4,6,12,1)";
      ctx.fillRect(0, 0, w, h);

      const threshold = BASE_DIST();

      // Draw edges
      ctx.lineCap = "round";
      for (let i = 0; i < nodes.length; i++) {
        for (let j = i + 1; j < nodes.length; j++) {
          const dx = nodes[i].x - nodes[j].x;
          const dy = nodes[i].y - nodes[j].y;
          const dist = Math.sqrt(dx * dx + dy * dy);
          if (dist > threshold) continue;

          // Alpha: strongest when nodes are closest
          const proximity = 1 - dist / threshold;
          const alpha = proximity * proximity * 0.30;

          // Color: interpolate between electric blue and cyan based on proximity
          const r = Math.round(45  * (1 - proximity));
          const g = Math.round(111 + proximity * (229 - 111));
          ctx.strokeStyle = `rgba(${r},${g},255,${alpha.toFixed(3)})`;
          ctx.lineWidth = proximity * 1.0;
          ctx.beginPath();
          ctx.moveTo(nodes[i].x, nodes[i].y);
          ctx.lineTo(nodes[j].x, nodes[j].y);
          ctx.stroke();
        }
      }

      // Draw nodes — flat dot + single shadowBlur, no per-node gradient
      ctx.shadowColor = "rgba(45,111,247,0.65)";
      ctx.shadowBlur = 9;
      nodes.forEach(n => {
        const pulse = 0.5 + 0.5 * Math.sin(now * n.pulseSpeed + n.pulseOffset);
        const alpha = 0.45 + pulse * 0.45;
        const glowR = n.r + pulse * 1.4;
        ctx.fillStyle = `rgba(94,148,255,${alpha.toFixed(3)})`;
        ctx.beginPath();
        ctx.arc(n.x, n.y, glowR, 0, Math.PI * 2);
        ctx.fill();
      });
      ctx.shadowBlur = 0;

      raf = requestAnimationFrame(tick);
    }
    tick(0);

    return () => {
      if (raf) cancelAnimationFrame(raf);
      ro.disconnect();
      visObs.disconnect();
      document.removeEventListener("visibilitychange", checkPaused);
    };
  }, []);

  return (
    <canvas ref={ref}
      style={{ position: "absolute", inset: 0, width: "100%", height: "100%", display: "block" }} />
  );
}

// ── Contato page ──────────────────────────────────────────────────────────
function ContatoPage() {
  const [isMobile, setIsMobile] = React.useState(window.innerWidth < 768);
  const [intent, setIntent] = React.useState(null);
  const [openFaq, setOpenFaq] = React.useState(null);

  React.useEffect(() => {
    const h = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener("resize", h);
    return () => window.removeEventListener("resize", h);
  }, []);

  const paths = [
    {
      id: "escola",
      icon: "◈",
      title: "Escola",
      desc: "Leve a física até os seus alunos.",
      color: [45, 111, 247],
      href: "./levar.html",
    },
    {
      id: "parceiro",
      icon: "◇",
      title: "Parcerias",
      desc: "Empresas, fundações e instituições.",
      color: [107, 63, 255],
      href: "./parceria.html",
    },
    {
      id: "outro",
      icon: "○",
      title: "Imprensa / Outros",
      desc: "Jornalistas, pesquisadores, curiosos.",
      color: [0, 229, 255],
      href: null,
    },
  ];

  const faqs = [
    { q: "O projeto cobra algum valor das escolas?", a: "Não. Todas as visitas e kits são oferecidos sem custo para escolas e alunos. O projeto é financiado por doações e parceiros." },
    { q: "Como funciona o processo de agendamento?", a: "Após o envio do formulário, entramos em contato em até 48h para alinhar data, número de alunos e experimentos mais adequados." },
    { q: "O projeto atende fora de Goiás?", a: "Visitas presenciais ainda se concentram em Goiás, mas estamos desenvolvendo kits que podem ser enviados para qualquer estado do Brasil." },
    { q: "Posso fazer uma doação pontual?", a: "Sim. Acesse a página de apoio — toda doação, de qualquer valor, vai direto para materiais e transporte." },
    { q: "Como citar o projeto na imprensa?", a: "Física Além do Papel é um projeto de extensão voluntário nascido na IYPT 2024, em Goiânia. Para fotos, vídeos e declarações, entre em contato pelo formulário abaixo." },
  ];

  const selectedPath = paths.find(p => p.id === intent);

  return (
    <>
      <PageHeader backHref="./index.html" backLabel="← Início" />

      {/* Hero */}
      <section className="grain" style={{
        position: "relative", minHeight: isMobile ? "56vh" : "64vh",
        paddingTop: isMobile ? 100 : 130, paddingBottom: isMobile ? 48 : 64,
        background: "radial-gradient(ellipse at 50% 40%, #060918 0%, #060810 50%, #04060C 100%)",
        overflow: "hidden",
        display: "flex", flexDirection: "column", justifyContent: "center",
      }}>
        <ConnectionNetwork />

        <div aria-hidden="true" style={{
          position: "absolute", inset: 0,
          background: "radial-gradient(ellipse at 50% 50%, rgba(4,6,12,0.60) 0%, transparent 70%)",
          pointerEvents: "none",
        }} />

        <div className="container" style={{ position: "relative", zIndex: 2, textAlign: "center" }}>
          <div style={{
            display: "flex", alignItems: "center", justifyContent: "center", gap: 16,
            marginBottom: 28, animation: "heroReveal 0.7s ease-out both",
          }}>
            <div style={{ width: 28, height: 1, background: "linear-gradient(90deg, transparent, rgba(45,111,247,0.4))" }} />
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fg-4)", letterSpacing: "0.34em", textTransform: "uppercase" }}>Contato</span>
            <div style={{ width: 28, height: 1, background: "linear-gradient(90deg, rgba(45,111,247,0.4), transparent)" }} />
          </div>

          <h1 style={{
            fontFamily: "var(--font-display)",
            fontSize: isMobile ? "clamp(26px, 7vw, 44px)" : "clamp(36px, 5vw, 64px)",
            fontWeight: 300, lineHeight: 1.06, letterSpacing: "-0.03em",
            color: "var(--fg-1)", margin: "0 auto", maxWidth: 700,
            animation: "heroReveal 0.8s 0.1s ease-out both",
          }}>
            O que você precisa,{" "}
            <span style={{
              fontWeight: 500,
              background: "linear-gradient(135deg, #2D6FF7 0%, #00E5FF 100%)",
              WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent", backgroundClip: "text",
            }}>a gente escuta</span>.
          </h1>

          <p style={{
            fontFamily: "var(--font-body)", fontSize: isMobile ? 15 : 17, lineHeight: 1.65,
            color: "var(--fg-2)", maxWidth: 480, margin: "20px auto 0",
            animation: "heroReveal 0.8s 0.2s ease-out both",
          }}>
            Escolha o caminho que faz sentido para você — e vamos conversar.
          </p>
        </div>
      </section>

      {/* Path selector */}
      <section className="section" style={{
        background: "linear-gradient(180deg, #04060C 0%, #07090F 100%)",
      }}>
        <div className="container">
          <div className="overline-row">Escolha o seu caminho</div>

          <div style={{
            display: "grid",
            gridTemplateColumns: isMobile ? "1fr" : "repeat(3, 1fr)",
            gap: 16, marginBottom: 56,
          }}>
            {paths.map(path => {
              const [r, g, b] = path.color;
              const isSelected = intent === path.id;
              return (
                <div
                  key={path.id}
                  onClick={() => {
                    if (path.href) window.location.href = path.href;
                    else setIntent(path.id);
                  }}
                  style={{
                    background: isSelected ? `rgba(${r},${g},${b},0.07)` : "var(--deep)",
                    border: `1px solid ${isSelected ? `rgba(${r},${g},${b},0.50)` : "var(--line)"}`,
                    borderRadius: "var(--r-xl)", padding: "28px 24px",
                    cursor: "pointer",
                    transition: "all 0.28s var(--ease-out)",
                    boxShadow: isSelected ? `0 0 40px rgba(${r},${g},${b},0.14)` : "0 1px 0 rgba(255,255,255,0.04) inset",
                    position: "relative", overflow: "hidden",
                  }}
                  onMouseOver={(e) => {
                    if (!isSelected) {
                      e.currentTarget.style.border = `1px solid rgba(${r},${g},${b},0.32)`;
                      e.currentTarget.style.background = `rgba(${r},${g},${b},0.04)`;
                    }
                  }}
                  onMouseOut={(e) => {
                    if (!isSelected) {
                      e.currentTarget.style.border = "1px solid var(--line)";
                      e.currentTarget.style.background = "var(--deep)";
                    }
                  }}
                >
                  <div style={{
                    position: "absolute", top: 0, left: 20, right: 20, height: 1,
                    background: `linear-gradient(90deg, transparent, rgba(${r},${g},${b},${isSelected ? 0.55 : 0.20}), transparent)`,
                  }} />

                  <div style={{
                    fontSize: 28, marginBottom: 16,
                    color: `rgba(${r},${g},${b},0.85)`,
                  }}>{path.icon}</div>

                  <div style={{
                    fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 500,
                    color: "var(--fg-1)", marginBottom: 10, letterSpacing: "-0.01em",
                  }}>{path.title}</div>

                  <div style={{
                    fontSize: 14, lineHeight: 1.55, color: "var(--fg-3)",
                    marginBottom: 20,
                  }}>{path.desc}</div>

                  <div style={{
                    fontFamily: "var(--font-display)", fontSize: 13,
                    color: `rgba(${r},${g},${b},0.8)`,
                    display: "flex", alignItems: "center", gap: 6,
                  }}>
                    {path.href ? "Ir para a página" : "Usar formulário"} →
                  </div>
                </div>
              );
            })}
          </div>

          {/* Form for "Imprensa / Outros" intent */}
          {intent === "outro" && (
            <div style={{ maxWidth: 560, margin: "0 auto" }}>
              <form 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={(e) => { e.preventDefault(); alert("Enviado! (mockup)"); }}>
                <div style={{
                  position: "absolute", top: 0, left: 28, right: 28, height: 1,
                  background: "linear-gradient(90deg, transparent, var(--plasma-cyan) 50%, transparent)",
                }} />

                <div style={{
                  fontFamily: "var(--font-mono)", fontSize: 10,
                  color: "var(--plasma-cyan)", letterSpacing: "0.22em",
                  textTransform: "uppercase", marginBottom: 20,
                }}>Contato direto</div>

                <ContatoField label="Nome" placeholder="Seu nome completo" />
                <ContatoField label="E-mail" placeholder="seu@email.com" />
                <ContatoField label="Veículo / Instituição" placeholder="Opcional — jornal, universidade, etc." />

                <div style={{ marginBottom: 22 }}>
                  <div style={{
                    fontFamily: "var(--font-mono)", fontSize: 10,
                    color: "var(--fg-3)", letterSpacing: "0.22em",
                    textTransform: "uppercase", marginBottom: 8,
                  }}>Mensagem</div>
                  <textarea rows={5} placeholder="Qual é o assunto?" 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",
                  }} />
                </div>

                <button type="submit" className="btn btn-primary"
                  style={{ width: "100%", justifyContent: "center" }}>
                  Enviar <span className="arrow">→</span>
                </button>
                <div style={{
                  marginTop: 12, textAlign: "center",
                  fontFamily: "var(--font-mono)", fontSize: 10,
                  color: "var(--fg-3)", letterSpacing: "0.14em", textTransform: "uppercase",
                }}>Resposta em até 48h úteis</div>
              </form>
            </div>
          )}

          {/* Direct contact + Instagram */}
          <div style={{
            marginTop: 56, paddingTop: 40, borderTop: "1px solid var(--line)",
            display: "flex", flexDirection: isMobile ? "column" : "row",
            gap: isMobile ? 24 : 48, alignItems: isMobile ? "flex-start" : "center",
            justifyContent: "center",
          }}>
            <div>
              <div style={{
                fontFamily: "var(--font-mono)", fontSize: 10,
                color: "var(--fg-3)", letterSpacing: "0.22em", textTransform: "uppercase",
                marginBottom: 10,
              }}>Instagram</div>
              <a href="https://instagram.com/fisicaalemdopapel" target="_blank" rel="noopener noreferrer"
                style={{
                  fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 500,
                  color: "var(--fg-1)", textDecoration: "none",
                }}>@fisicaalemdopapel</a>
            </div>
            <div style={{ width: 1, height: 40, background: "var(--line)", display: isMobile ? "none" : "block" }} />
            <div>
              <div style={{
                fontFamily: "var(--font-mono)", fontSize: 10,
                color: "var(--fg-3)", letterSpacing: "0.22em", textTransform: "uppercase",
                marginBottom: 10,
              }}>Localização base</div>
              <div style={{
                fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 500,
                color: "var(--fg-1)",
              }}>Goiânia, Goiás — Brasil</div>
            </div>
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section className="section-tight" style={{
        background: "var(--void)", borderTop: "1px solid var(--line)",
      }}>
        <div className="container">
          <div style={{ maxWidth: 680, margin: "0 auto" }}>
            <div className="overline-row">Perguntas frequentes</div>

            {faqs.map((faq, i) => (
              <div key={i} style={{
                borderBottom: "1px solid var(--line)",
                padding: "20px 0",
              }}>
                <button
                  onClick={() => setOpenFaq(openFaq === i ? null : i)}
                  style={{
                    width: "100%", textAlign: "left",
                    display: "flex", justifyContent: "space-between", alignItems: "center",
                    gap: 16, background: "none", border: "none",
                    fontFamily: "var(--font-display)", fontSize: isMobile ? 15 : 16,
                    fontWeight: 500, color: "var(--fg-1)", cursor: "pointer",
                    padding: 0,
                  }}>
                  <span>{faq.q}</span>
                  <span style={{
                    color: "var(--fg-3)", fontSize: 18, flexShrink: 0,
                    transform: openFaq === i ? "rotate(45deg)" : "none",
                    transition: "transform 0.22s",
                    display: "inline-block",
                  }}>+</span>
                </button>
                {openFaq === i && (
                  <p style={{
                    marginTop: 14, marginBottom: 0,
                    fontSize: 15, lineHeight: 1.7,
                    color: "var(--fg-2)",
                    animation: "heroReveal 0.25s ease-out both",
                  }}>{faq.a}</p>
                )}
              </div>
            ))}
          </div>
        </div>
      </section>

      <Footer />
    </>
  );
}

function ContatoField({ label, placeholder }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{
        fontFamily: "var(--font-mono)", fontSize: 10,
        color: "var(--fg-3)", letterSpacing: "0.22em",
        textTransform: "uppercase", marginBottom: 7,
      }}>{label}</div>
      <input placeholder={placeholder} 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 = "var(--electric)"; e.target.style.boxShadow = "0 0 0 3px rgba(45,111,247,0.18)"; }}
      onBlur={(e) => { e.target.style.borderColor = "var(--line-strong)"; e.target.style.boxShadow = "none"; }}
      />
    </div>
  );
}

const contatoRoot = ReactDOM.createRoot(document.getElementById("root"));
contatoRoot.render(<ContatoPage />);
