// Levar.jsx — "Levar à Escola / Apoiar" merged destination page.
// Hero: FlowFieldCanvas — hundreds of particles following an evolving vector field.
// Trails accumulate on the canvas creating dense flowing streamlines of light.
// Inspired by electromagnetic field lines and fluid streamlines.

function FlowFieldCanvas() {
  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 raf = null, w = 0, h = 0;
    let paused = document.hidden;

    // Colour palette — site tokens only
    const PALETTE = [
      [45,  111, 247],   // electric blue  (dominant)
      [45,  111, 247],   // electric blue  (weight x2)
      [0,   229, 255],   // plasma cyan
      [94,  148, 255],   // electric soft
      [107, 63,  255],   // plasma violet
    ];

    // Particles
    const N = window.innerWidth < 768 ? 180 : 340;
    let particles = [];

    function mkParticle() {
      return {
        x: Math.random() * w,
        y: Math.random() * h,
        age: Math.floor(Math.random() * 280),
        maxAge: 160 + Math.random() * 240,
        speed: 0.38 + Math.random() * 0.42,
        col: PALETTE[Math.floor(Math.random() * PALETTE.length)],
      };
    }

    function resize() {
      const rect = canvas.getBoundingClientRect();
      w = rect.width; h = rect.height;
      canvas.width  = w * dpr;
      canvas.height = h * dpr;
      ctx.scale(dpr, dpr);
      // Hard clear + dark fill on resize so trails don't smear
      ctx.fillStyle = "rgba(4,6,12,1)";
      ctx.fillRect(0, 0, w, h);
      particles = Array.from({ length: N }, mkParticle);
    }
    resize();
    const ro = new ResizeObserver(resize);
    ro.observe(canvas);

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

    // Smooth pseudo-noise angle using overlaid sine waves at different scales.
    // Returns a direction in radians that varies smoothly across space and time.
    function fieldAngle(x, y, t) {
      const s = 0.0025;        // spatial frequency
      const ts = 0.00025;      // temporal drift speed
      return (
        Math.sin(x * s       + t * ts        ) * Math.PI +
        Math.sin(y * s * 0.8 + t * ts * 0.7  ) * Math.PI * 0.8 +
        Math.sin(x * s * 1.6 + y * s * 0.6   + t * ts * 1.4) * Math.PI * 0.5 +
        Math.cos(x * s * 0.4 + y * s * 1.8   + t * ts * 0.6) * Math.PI * 0.3
      );
    }

    let elapsed = 0;
    let prevTime = null;

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

      // Fast fade — keeps ~10 frames of bright trail, old history disappears quickly
      ctx.fillStyle = "rgba(4,6,12,0.18)";
      ctx.fillRect(0, 0, w, h);

      ctx.lineCap = "round";

      for (const p of particles) {
        p.age += 1;
        if (p.age > p.maxAge) {
          // Respawn at random position
          p.x = Math.random() * w;
          p.y = Math.random() * h;
          p.age = 0;
          p.maxAge = 160 + Math.random() * 240;
          p.speed = 1.0 + Math.random() * 1.2;
          p.col = PALETTE[Math.floor(Math.random() * PALETTE.length)];
          continue;
        }

        const angle = fieldAngle(p.x, p.y, elapsed);
        const nx = p.x + Math.cos(angle) * p.speed;
        const ny = p.y + Math.sin(angle) * p.speed;

        // Alpha: ramp in, hold, ramp out
        const lifeN = p.age / p.maxAge;
        const alpha = lifeN < 0.12 ? lifeN / 0.12
                    : lifeN > 0.80 ? (1 - lifeN) / 0.20
                    : 1;

        const [r, g, b] = p.col;
        ctx.strokeStyle = `rgba(${r},${g},${b},${(alpha * 0.52).toFixed(3)})`;
        ctx.lineWidth   = 0.55 + alpha * 0.65;
        ctx.beginPath();
        ctx.moveTo(p.x, p.y);
        ctx.lineTo(nx, ny);
        ctx.stroke();

        // Wrap edges
        p.x = ((nx % w) + w) % w;
        p.y = ((ny % h) + h) % h;
      }

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

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

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

// ── Levar page ────────────────────────────────────────────────────────────
function LevarPage() {
  const [isMobile, setIsMobile] = React.useState(window.innerWidth < 768);
  const [activeTab, setActiveTab] = React.useState("escola");
  const [formType, setFormType] = React.useState("escola");

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

  const tabs = [
    { id: "escola",    label: "Para Escolas",       icon: "◈" },
    { id: "apoiar",    label: "Para Apoiadores",     icon: "◇" },
    { id: "inst",      label: "Para Instituições",   icon: "○" },
  ];

  const content = {
    escola: {
      title: "A física pode chegar à sua escola.",
      desc: "Levamos experimentos reais, montados e mediados por voluntários. Sem custo. Sem burocracia. Apenas ciência que acontece na mão dos alunos.",
      items: [
        { label: "Visita presencial", desc: "Nossa equipe vai até você com os kits montados." },
        { label: "Kit experimental", desc: "Enviamos um kit para a escola realizar os experimentos de forma autônoma." },
        { label: "Duração", desc: "2 a 4 horas de experimentação, adaptada ao seu currículo." },
        { label: "Nível", desc: "Ensino fundamental II e médio — adaptamos para o seu público." },
      ],
    },
    apoiar: {
      title: "Cada apoio vira experimento real.",
      desc: "O projeto é 100% voluntário. Cada real arrecadado se transforma em material, transporte ou um kit experimental enviado a uma escola distante.",
      items: [
        { label: "Doação pontual", desc: "Qualquer valor ajuda a montar novos kits e custear deslocamentos." },
        { label: "Doação recorrente", desc: "Sustenta o projeto a longo prazo, permitindo planejamento e expansão." },
        { label: "Doação de materiais", desc: "Materiais de laboratório, ferramentas, embalagens para kits." },
        { label: "Divulgação", desc: "Compartilhar o projeto também é apoiar — amplia nosso alcance." },
      ],
    },
    inst: {
      title: "Parceria com impacto mensurável.",
      desc: "Secretarias de educação, fundações, ONGs e órgãos públicos podem ampliar o alcance do projeto e trazer ciência experimental a regiões inteiras.",
      items: [
        { label: "Secretarias de Educação", desc: "Integração curricular com visitas e kits em escala municipal ou estadual." },
        { label: "Fundações e ONGs", desc: "Copatrocínio de kits e visitas para comunidades específicas." },
        { label: "Órgãos Públicos", desc: "Projetos de extensão e divulgação científica com impacto direto." },
        { label: "Universidades", desc: "Colaboração acadêmica — pesquisa, IC e desenvolvimento de novos experimentos." },
      ],
    },
  };

  const cur = content[activeTab];

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

      {/* Hero */}
      <section id="top" className="grain" style={{
        position: "relative", minHeight: isMobile ? "62vh" : "70vh",
        paddingTop: isMobile ? 100 : 130, paddingBottom: isMobile ? 56 : 80,
        background: "#04060C",
        overflow: "hidden",
        display: "flex", flexDirection: "column", justifyContent: "center",
      }}>
        <FlowFieldCanvas />

        <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(--electric-soft)", letterSpacing: "0.34em", textTransform: "uppercase" }}>Levar · Apoiar</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, 72px)",
            fontWeight: 300, lineHeight: 1.06, letterSpacing: "-0.03em",
            color: "var(--fg-1)", margin: "0 auto", maxWidth: 820,
            animation: "heroReveal 0.8s 0.1s ease-out both",
          }}>
            A física vai{" "}
            <span style={{
              fontWeight: 500,
              background: "linear-gradient(135deg, #2D6FF7 0%, #5E94FF 50%, #00E5FF 100%)",
              WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent", backgroundClip: "text",
            }}>onde você está</span>.
          </h1>

          <p style={{
            fontFamily: "var(--font-body)", fontSize: isMobile ? 15 : 17, lineHeight: 1.65,
            color: "var(--fg-2)", maxWidth: 560, margin: "22px auto 0",
            animation: "heroReveal 0.8s 0.2s ease-out both",
          }}>
            Leve experimentos reais de física para a sua escola, apoie o projeto ou
            estabeleça uma parceria institucional que expande o alcance da ciência experimental.
          </p>

          <div style={{
            display: "flex", gap: 14, justifyContent: "center", flexWrap: "wrap",
            marginTop: 36, animation: "heroReveal 0.8s 0.3s ease-out both",
          }}>
            <a href="#acao" className="btn btn-primary">
              Quero participar <span className="arrow">→</span>
            </a>
            <a href="#kits" className="btn btn-secondary">
              Kits experimentais
            </a>
          </div>
        </div>
      </section>

      {/* Kits highlight section */}
      <section id="kits" className="section-tight" style={{
        background: "linear-gradient(180deg, #04060C 0%, #07090F 100%)",
        borderTop: "1px solid var(--line)",
        borderBottom: "1px solid var(--line)",
      }}>
        <div className="container">
          <div style={{
            display: "grid",
            gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr",
            gap: isMobile ? 36 : 64,
            alignItems: "center",
          }}>
            <div>
              <div className="overline-row" style={{ marginBottom: 20 }}>Kits Experimentais</div>
              <h2 style={{
                fontFamily: "var(--font-display)",
                fontSize: "clamp(24px, 3.5vw, 44px)",
                fontWeight: 400, lineHeight: 1.1, letterSpacing: "-0.025em",
                color: "var(--fg-1)", margin: "0 0 20px",
              }}>
                Ciência que viaja pelo correio.
              </h2>
              <p style={{ fontSize: 16, lineHeight: 1.7, color: "var(--fg-2)", margin: 0 }}>
                Desenvolvemos kits experimentais compactos que podem ser enviados a qualquer escola
                do Brasil. A equipe não precisa estar presente — os experimentos chegam prontos
                para acontecer na mão dos alunos.
              </p>
              <p style={{ fontSize: 16, lineHeight: 1.7, color: "var(--fg-2)", marginTop: 16 }}>
                A física além das barreiras geográficas. Além do laboratório.
                Além do papel.
              </p>
            </div>

            <div style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 14,
            }}>
              {[
                { icon: "◈", label: "Experimento completo", desc: "Materiais, instruções e guia pedagógico inclusos." },
                { icon: "◇", label: "Enviado pelos Correios", desc: "Chega onde a equipe ainda não chegou." },
                { icon: "○", label: "Sem custo para a escola", desc: "Financiado por apoiadores e parceiros." },
                { icon: "△", label: "Qualquer nível", desc: "Adaptado para EF II e EM." },
              ].map(item => (
                <div key={item.label} style={{
                  background: "var(--deep)", border: "1px solid var(--line)",
                  borderRadius: "var(--r-lg)", padding: "20px 18px",
                  boxShadow: "0 1px 0 rgba(255,255,255,0.04) inset",
                }}>
                  <div style={{
                    fontSize: 20, color: "var(--electric-soft)", marginBottom: 10,
                  }}>{item.icon}</div>
                  <div style={{
                    fontFamily: "var(--font-display)", fontSize: 13, fontWeight: 500,
                    color: "var(--fg-1)", marginBottom: 6, letterSpacing: "-0.01em",
                  }}>{item.label}</div>
                  <div style={{ fontSize: 12.5, color: "var(--fg-3)", lineHeight: 1.55 }}>{item.desc}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* Tabbed content */}
      <section id="acao" className="section" style={{
        background: "linear-gradient(180deg, #07090F 0%, var(--void) 100%)",
      }}>
        <div className="container">
          <div className="overline-row">Como participar</div>

          {/* Tab selector */}
          <div style={{
            display: "flex", gap: 8, flexWrap: "wrap",
            marginBottom: isMobile ? 32 : 48,
          }}>
            {tabs.map(tab => (
              <button key={tab.id} onClick={() => setActiveTab(tab.id)} style={{
                fontFamily: "var(--font-display)", fontSize: 14, fontWeight: activeTab === tab.id ? 600 : 400,
                padding: "10px 20px", borderRadius: "var(--r-pill)",
                border: activeTab === tab.id ? "1px solid rgba(45,111,247,0.55)" : "1px solid var(--line-strong)",
                background: activeTab === tab.id ? "rgba(45,111,247,0.10)" : "transparent",
                color: activeTab === tab.id ? "var(--electric-soft)" : "var(--fg-2)",
                cursor: "pointer", transition: "all 0.22s var(--ease-out)",
                display: "flex", alignItems: "center", gap: 8,
              }}>
                <span style={{ opacity: 0.7 }}>{tab.icon}</span>
                {tab.label}
              </button>
            ))}
          </div>

          {/* Tab content */}
          <div style={{
            display: "grid",
            gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr",
            gap: isMobile ? 32 : 64,
            alignItems: "start",
          }}>
            <div>
              <h2 style={{
                fontFamily: "var(--font-display)",
                fontSize: "clamp(22px, 3vw, 38px)",
                fontWeight: 400, lineHeight: 1.1, letterSpacing: "-0.025em",
                color: "var(--fg-1)", margin: "0 0 18px",
              }}>{cur.title}</h2>
              <p style={{ fontSize: 16, lineHeight: 1.7, color: "var(--fg-2)", margin: 0 }}>
                {cur.desc}
              </p>

              <div style={{
                display: "flex", flexDirection: "column", gap: 16, marginTop: 32,
              }}>
                {cur.items.map(item => (
                  <div key={item.label} style={{
                    display: "grid", gridTemplateColumns: "24px 1fr", gap: 14,
                    alignItems: "start",
                  }}>
                    <div style={{
                      width: 6, height: 6, borderRadius: "50%",
                      background: "var(--electric)", marginTop: 8,
                      boxShadow: "0 0 8px rgba(45,111,247,0.7)",
                    }} />
                    <div>
                      <div style={{
                        fontFamily: "var(--font-display)", fontSize: 15, fontWeight: 500,
                        color: "var(--fg-1)", marginBottom: 4,
                      }}>{item.label}</div>
                      <div style={{ fontSize: 14, lineHeight: 1.6, color: "var(--fg-3)" }}>{item.desc}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Form */}
            <div>
              <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(--electric) 50%, transparent)",
                }} />

                <div style={{
                  fontFamily: "var(--font-mono)", fontSize: 10,
                  color: "var(--electric-soft)", letterSpacing: "0.22em",
                  textTransform: "uppercase", marginBottom: 20,
                }}>Enviar interesse</div>

                <LevarField label="Nome" placeholder="Seu nome completo" />
                <LevarField label="E-mail" placeholder="contato@..." />
                <LevarField label="Instituição / cidade" placeholder="Nome da escola, cidade, estado..." />

                <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={4}
                    placeholder="Como podemos ajudar? Contexto, número de alunos, prazo..."
                    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", padding: "15px 24px" }}>
                  Enviar interesse <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",
                }}>Respondemos em até 48h úteis</div>
              </form>
            </div>
          </div>
        </div>
      </section>

      <Footer />
    </>
  );
}

function LevarField({ 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 levarRoot = ReactDOM.createRoot(document.getElementById("root"));
levarRoot.render(<LevarPage />);
