/* ============== HERO with canvas starfield + orbital moon =============== */

const HeroCanvas = ({ intensity = "high" }) => {
  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, 2);
    let raf, w, h, stars, shooters;
    const intensityFactor = intensity === "low" ? 0.25 : intensity === "medium" ? 0.55 : 1;

    const resize = () => {
      const rect = canvas.getBoundingClientRect();
      w = rect.width; h = rect.height;
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      seed();
    };

    const seed = () => {
      const count = Math.floor((w * h) / 9000 * intensityFactor);
      stars = Array.from({ length: count }, () => ({
        x: Math.random() * w,
        y: Math.random() * h,
        z: Math.random() * 0.85 + 0.15,
        vx: (Math.random() - 0.5) * 0.04,
        vy: (Math.random() - 0.5) * 0.04,
        tw: Math.random() * Math.PI * 2,
        twS: Math.random() * 0.02 + 0.005,
      }));
      shooters = [];
    };

    const spawnShooter = () => {
      if (intensity === "low") return;
      if (Math.random() > 0.012 * intensityFactor) return;
      shooters.push({
        x: Math.random() * w * 0.5,
        y: Math.random() * h * 0.3,
        vx: 2 + Math.random() * 2,
        vy: 0.8 + Math.random() * 0.8,
        life: 1,
        len: 80 + Math.random() * 60,
      });
    };

    const draw = () => {
      ctx.clearRect(0, 0, w, h);

      // soft nebula glow
      const grad = ctx.createRadialGradient(w * 0.7, h * 0.5, 0, w * 0.7, h * 0.5, Math.max(w, h) * 0.6);
      grad.addColorStop(0, "rgba(91, 141, 239, 0.10)");
      grad.addColorStop(0.45, "rgba(91, 141, 239, 0.04)");
      grad.addColorStop(1, "rgba(0, 0, 0, 0)");
      ctx.fillStyle = grad;
      ctx.fillRect(0, 0, w, h);

      // stars
      for (const s of stars) {
        s.x += s.vx * s.z;
        s.y += s.vy * s.z;
        s.tw += s.twS;
        if (s.x < 0) s.x = w; if (s.x > w) s.x = 0;
        if (s.y < 0) s.y = h; if (s.y > h) s.y = 0;
        const a = (Math.sin(s.tw) * 0.5 + 0.5) * 0.85 + 0.15;
        const r = s.z * 1.4;
        ctx.beginPath();
        ctx.fillStyle = `rgba(${220 + Math.floor(s.z * 35)}, ${230}, 255, ${a * s.z})`;
        ctx.arc(s.x, s.y, r, 0, Math.PI * 2);
        ctx.fill();
      }

      // shooting stars
      spawnShooter();
      for (let i = shooters.length - 1; i >= 0; i--) {
        const sh = shooters[i];
        sh.x += sh.vx;
        sh.y += sh.vy;
        sh.life -= 0.012;
        if (sh.life <= 0 || sh.x > w + 100 || sh.y > h + 100) {
          shooters.splice(i, 1); continue;
        }
        const tailX = sh.x - sh.vx * (sh.len / 4);
        const tailY = sh.y - sh.vy * (sh.len / 4);
        const lg = ctx.createLinearGradient(sh.x, sh.y, tailX, tailY);
        lg.addColorStop(0, `rgba(180, 210, 255, ${sh.life})`);
        lg.addColorStop(1, "rgba(180, 210, 255, 0)");
        ctx.strokeStyle = lg;
        ctx.lineWidth = 1.2;
        ctx.beginPath();
        ctx.moveTo(sh.x, sh.y);
        ctx.lineTo(tailX, tailY);
        ctx.stroke();
      }

      raf = requestAnimationFrame(draw);
    };

    resize();
    draw();
    window.addEventListener("resize", resize);
    return () => { window.removeEventListener("resize", resize); cancelAnimationFrame(raf); };
  }, [intensity]);
  return <canvas ref={ref} className="hero-canvas" />;
};

/* ============== Moon / Orbit SVG =============== */

const HeroOrbit = ({ intensity = "high" }) => {
  const speed = intensity === "low" ? 0 : intensity === "medium" ? 0.4 : 1;
  const [t, setT] = React.useState(0);
  React.useEffect(() => {
    if (speed === 0) return;
    let raf, last = performance.now();
    const tick = (now) => {
      const dt = (now - last) / 1000;
      last = now;
      setT((p) => p + dt * speed);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [speed]);

  return (
    <div className="hero-orbit">
      <svg viewBox="-280 -280 560 560" width="100%" height="100%" style={{ overflow: "visible" }}>
        <defs>
          <radialGradient id="moonBody" cx="0.35" cy="0.35">
            <stop offset="0" stopColor="#f3f6ff" />
            <stop offset="0.4" stopColor="#c9d4ee" />
            <stop offset="0.85" stopColor="#5d7099" />
            <stop offset="1" stopColor="#1d2540" />
          </radialGradient>
          <radialGradient id="moonGlow" cx="0.5" cy="0.5">
            <stop offset="0" stopColor="rgba(138, 175, 255, 0.55)" />
            <stop offset="0.5" stopColor="rgba(91, 141, 239, 0.15)" />
            <stop offset="1" stopColor="rgba(0,0,0,0)" />
          </radialGradient>
          <filter id="moonShadow">
            <feGaussianBlur stdDeviation="1.2" />
          </filter>
          <radialGradient id="craterGrad">
            <stop offset="0" stopColor="rgba(20, 28, 50, 0.7)" />
            <stop offset="1" stopColor="rgba(20, 28, 50, 0)" />
          </radialGradient>
        </defs>

        {/* outer glow */}
        <circle cx="0" cy="0" r="240" fill="url(#moonGlow)" />

        {/* orbit rings */}
        {[200, 235, 268].map((r, i) => (
          <circle
            key={r}
            cx="0" cy="0" r={r}
            fill="none"
            stroke="rgba(91, 141, 239, 0.18)"
            strokeWidth="1"
            strokeDasharray={i === 1 ? "2 6" : i === 2 ? "1 10" : "0"}
            transform={`rotate(${t * (i + 1) * 6})`}
            style={{ transformOrigin: "0 0" }}
          />
        ))}

        {/* moon body */}
        <circle cx="0" cy="0" r="160" fill="url(#moonBody)" />

        {/* moon craters */}
        <g filter="url(#moonShadow)" opacity="0.85">
          <ellipse cx="-40" cy="-50" rx="22" ry="20" fill="url(#craterGrad)" />
          <ellipse cx="30" cy="20" rx="32" ry="28" fill="url(#craterGrad)" />
          <ellipse cx="-60" cy="60" rx="18" ry="16" fill="url(#craterGrad)" />
          <ellipse cx="60" cy="-80" rx="14" ry="13" fill="url(#craterGrad)" />
          <ellipse cx="80" cy="70" rx="10" ry="10" fill="url(#craterGrad)" />
          <ellipse cx="-90" cy="-20" rx="8" ry="8" fill="url(#craterGrad)" />
          <ellipse cx="20" cy="100" rx="9" ry="9" fill="url(#craterGrad)" />
          <ellipse cx="-20" cy="-110" rx="6" ry="6" fill="url(#craterGrad)" />
        </g>

        {/* terminator shadow */}
        <circle cx="0" cy="0" r="160" fill="url(#terminator)" />
        <defs>
          <radialGradient id="terminator" cx="0.85" cy="0.5" r="0.9">
            <stop offset="0.45" stopColor="rgba(0,0,0,0)" />
            <stop offset="1" stopColor="rgba(0,0,0,0.65)" />
          </radialGradient>
        </defs>

        {/* orbiting satellites */}
        {[
          { r: 200, speed: 1.2, size: 4, color: "#8aafff", offset: 0 },
          { r: 235, speed: -0.7, size: 3, color: "#c9d4ee", offset: 1.5 },
          { r: 268, speed: 0.4, size: 2.5, color: "#5b8def", offset: 3 },
        ].map((s, i) => {
          const a = t * s.speed + s.offset;
          const x = Math.cos(a) * s.r;
          const y = Math.sin(a) * s.r;
          return (
            <g key={i}>
              <circle cx={x} cy={y} r={s.size * 3} fill={s.color} opacity="0.15" />
              <circle cx={x} cy={y} r={s.size} fill={s.color} />
            </g>
          );
        })}

        {/* tick marks ring */}
        <g opacity="0.4">
          {Array.from({ length: 48 }).map((_, i) => {
            const a = (i / 48) * Math.PI * 2;
            const r1 = 185, r2 = i % 4 === 0 ? 195 : 190;
            return (
              <line
                key={i}
                x1={Math.cos(a) * r1} y1={Math.sin(a) * r1}
                x2={Math.cos(a) * r2} y2={Math.sin(a) * r2}
                stroke="rgba(138, 175, 255, 0.5)"
                strokeWidth="1"
              />
            );
          })}
        </g>

        {/* coordinate readout */}
        <text x="-260" y="-220" fill="rgba(138, 175, 255, 0.6)" fontFamily="JetBrains Mono, monospace" fontSize="10" letterSpacing="2">
          ORBIT/01 · LUNAR
        </text>
        <text x="180" y="240" fill="rgba(138, 175, 255, 0.6)" fontFamily="JetBrains Mono, monospace" fontSize="10" letterSpacing="2" textAnchor="end">
          {`SYS · ${Math.floor((t * 12) % 360).toString().padStart(3, "0")}°`}
        </text>
      </svg>
    </div>
  );
};

/* ============== HERO =============== */

const Hero = ({ tweaks }) => {
  const headline = tweaks.headline;
  const words = headline.split(" ");

  return (
    <header className={`hero hero-${tweaks.heroLayout}`}>
      <div className="hero-grad" />
      <HeroCanvas intensity={tweaks.animations} />

      <div className="wrap hero-grid-inner">
        <div className="hero-copy">
          <span className="eyebrow" style={{ animation: "rise 0.9s 0.2s var(--ease-out) both" }}>
            <span className="dot-sm" style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--accent-2)", boxShadow: "0 0 10px var(--accent-2)" }} />
            Fábrica de software · 2025
          </span>

          <h1 className="hero-headline">
            {words.map((w, i) => (
              <span
                key={i}
                className={`word ${w.startsWith("*") ? "italic" : ""}`}
                style={{ animationDelay: `${0.25 + i * 0.07}s` }}
              >
                {w.replace(/\*/g, "")}{i < words.length - 1 ? "\u00A0" : ""}
              </span>
            ))}
          </h1>

          <p className="hero-sub">
            Construímos sistemas internos sob medida que substituem planilhas, automatizam processos e devolvem tempo ao seu time. Software pensado para resolver não só para existir.
          </p>

          <div className="hero-actions">
            <a href="#contato" className="btn btn-primary">
              Começar um projeto
              <Icons.Arrow className="arrow" size={18} />
            </a>
            <a href="#cases" className="btn btn-ghost">
              Ver sistemas em produção
            </a>
          </div>

          <div className="hero-meta">
            <div className="meta">
              <b>2</b>
              <span>Sistemas em produção</span>
            </div>
            <div className="meta">
              <b>100%</b>
              <span>Sob medida</span>
            </div>
            <div className="meta">
              <b>24/7</b>
              <span>Operação contínua</span>
            </div>
          </div>
        </div>

        <HeroOrbit intensity={tweaks.animations} />
      </div>
    </header>
  );
};

window.Hero = Hero;
