/* global React, ReactDOM */
/* Homepage - cosmic gold redesign adapted from Captixy Home.dc.html */
const { useEffect: useHomeEffect, useRef: useHomeRef } = React;
const { LogoMark: HomeLogoMark } = window;

const HOME_GOLD = "#D4AF37";
const HOME_AMBER = "#B87333";
const HOME_PARCHMENT = "#0B0B0F";
const HOME_INK = "#E9E1D0";

function HomeArrow({ className = "w-4 h-4" }) {
  return (
    <svg
      viewBox="0 0 20 20"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      className={className}
      aria-hidden="true"
    >
      <path d="M4 10h12" />
      <path d="M11 5l5 5-5 5" />
    </svg>
  );
}

function HomeCheck({ className = "w-4 h-4", style }) {
  return (
    <svg
      viewBox="0 0 20 20"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      className={className}
      style={style}
      aria-hidden="true"
    >
      <path d="M4 10.5l4 4L16 6" />
    </svg>
  );
}

function CaptixyMonogram({ className = "w-6 h-6" }) {
  return (
    <svg
      viewBox="0 0 89 80"
      fill="currentColor"
      className={className}
      aria-hidden="true"
    >
      <g transform="translate(0,80) scale(0.1,-0.1)">
        <path d="M395 784 c-11 -2 -45 -9 -75 -15 -126 -25 -248 -125 -290 -237 -18 -47 -21 -72 -18 -142 5 -103 28 -159 93 -229 42 -45 150 -112 179 -111 14 1 176 217 176 235 0 8 -32 51 -71 96 -96 112 -103 123 -89 148 10 20 19 21 230 21 121 0 220 -3 220 -8 0 -4 -52 -77 -116 -162 -141 -188 -254 -345 -254 -354 0 -3 109 -5 243 -4 l242 3 0 100 0 100 -133 3 -132 3 57 72 c32 40 93 114 135 166 l78 93 0 102 c0 66 -4 106 -12 114 -9 9 -72 12 -227 11 -119 -1 -225 -3 -236 -5z" />
      </g>
    </svg>
  );
}

function ProductOrbGlyph({ tone, size = "md" }) {
  const isAssistant = tone === "assistant";
  const sizeClass =
    size === "lg" ? "w-14 h-14 rounded-2xl" : "w-12 h-12 rounded-[1rem]";
  return (
    <span
      className={`${sizeClass} inline-flex items-center justify-center text-white shrink-0`}
      style={{
        background: isAssistant
          ? "linear-gradient(135deg,#8A5526 0%,#CD9259 100%)"
          : "linear-gradient(135deg,#9C7C24 0%,#D4AF37 100%)",
        boxShadow: isAssistant
          ? "0 10px 26px rgba(184,115,51,0.40)"
          : "0 10px 26px rgba(212,175,55,0.36)",
      }}
    >
      <CaptixyMonogram className={size === "lg" ? "w-8 h-7" : "w-6 h-6"} />
    </span>
  );
}

function useCosmicCanvas(canvasRef, hostRef, variant) {
  useHomeEffect(() => {
    const canvas = canvasRef.current;
    const host = hostRef.current;
    if (!canvas || !host) return undefined;

    const reducedMotion = window.matchMedia(
      "(prefers-reduced-motion: reduce)",
    ).matches;
    const ctx = canvas.getContext("2d");
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    const rand = (min, max) => min + Math.random() * (max - min);
    const starColors = ["#E9E1D0", "#E8C96A", "#B87333", "#D4AF37"];
    let width = 0;
    let height = 0;
    let raf = 0;
    let stars = [];
    let dust = [];
    let nodes = [];
    let galaxies = [];
    let systems = [];
    let auroras = [];
    let band = [];
    let cluster = [];
    let shootingStar = null;
    let shootingTimer = 180;
    let mouseX = 0;
    let mouseY = 0;
    let targetX = 0;
    let targetY = 0;

    const buildGalaxy = (
      fx,
      fy,
      radius,
      arms,
      colorA,
      colorB,
      count,
      spin,
      tilt,
      rotationAngle,
    ) => {
      const points = [];
      for (let i = 0; i < count; i += 1) {
        const arm = i % arms;
        const t = Math.pow(Math.random(), 0.5);
        const r = t * radius;
        const baseAngle = (arm / arms) * Math.PI * 2;
        const angle = baseAngle + t * 4.4 + rand(-0.26, 0.26);
        const bright = Math.random() < 0.08;
        points.push({
          r,
          angle,
          size: (bright ? rand(1.4, 2.6) : rand(0.3, 1.4)) * (1 - t * 0.3),
          alpha: (1 - t) * 0.55 + 0.12,
          color: bright ? colorA : Math.random() < 0.5 ? colorA : colorB,
          phase: rand(0, Math.PI * 2),
          twinkle: bright,
        });
      }

      const halo = [];
      for (let i = 0; i < Math.round(count * 0.3); i += 1) {
        halo.push({
          r: Math.pow(Math.random(), 0.7) * radius * 1.15,
          angle: rand(0, Math.PI * 2),
          size: rand(0.2, 1),
          alpha: rand(0.04, 0.18),
          color: Math.random() < 0.5 ? colorA : colorB,
        });
      }

      return {
        fx,
        fy,
        radius,
        arms,
        points,
        halo,
        rotation: rand(0, Math.PI * 2),
        spin,
        tilt,
        rotationAngle,
        colorA,
      };
    };

    const build = () => {
      const rect = host.getBoundingClientRect();
      width = rect.width;
      height = rect.height;
      canvas.width = width * dpr;
      canvas.height = height * dpr;
      canvas.style.width = `${width}px`;
      canvas.style.height = `${height}px`;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

      const starCount = Math.min(
        240,
        Math.max(120, Math.round((width * height) / 8500)),
      );
      const nodeCount = Math.min(72, Math.max(28, Math.round(width / 18)));
      const minSide = Math.min(width, height);

      stars = Array.from({ length: starCount }, () => ({
        x: rand(0, width),
        y: rand(0, height),
        radius: rand(0.3, 1.5),
        a: rand(0.18, 0.9),
        twinkle: rand(0.004, 0.018),
        dir: Math.random() > 0.5 ? 1 : -1,
        color: starColors[Math.floor(Math.random() * starColors.length)],
      }));
      dust = Array.from({ length: 44 }, () => ({
        x: rand(0, width),
        y: rand(0, height),
        radius: rand(0.4, 1.7),
        vx: rand(-0.1, 0.1),
        vy: rand(0.05, 0.28),
        alpha: rand(0.08, 0.32),
      }));
      nodes = Array.from({ length: nodeCount }, () => ({
        x: rand(0, width),
        y: rand(0, height),
        vx: rand(-0.28, 0.28),
        vy: rand(-0.28, 0.28),
      }));

      galaxies = [
        buildGalaxy(
          0.18,
          0.28,
          minSide * 0.34,
          3,
          "212,175,55",
          "184,115,51",
          920,
          0.00075,
          0.4,
          -0.5,
        ),
        buildGalaxy(
          0.86,
          0.72,
          minSide * 0.24,
          4,
          "232,201,106",
          "184,115,51",
          700,
          -0.0011,
          0.52,
          0.7,
        ),
        buildGalaxy(
          0.64,
          0.13,
          minSide * 0.15,
          2,
          "212,175,55",
          "184,115,51",
          340,
          0.0016,
          0.46,
          1.4,
        ),
      ];
      systems = [
        {
          fx: 0.74,
          fy: 0.24,
          sun: "#E8C96A",
          glow: "212,175,55",
          planets: [
            {
              r: minSide * 0.045,
              angle: rand(0, Math.PI * 2),
              speed: 0.024,
              size: 2.3,
              color: "#D4AF37",
            },
            {
              r: minSide * 0.075,
              angle: rand(0, Math.PI * 2),
              speed: 0.014,
              size: 3,
              color: "#B87333",
            },
          ],
        },
        {
          fx: 0.09,
          fy: 0.81,
          sun: "#B87333",
          glow: "184,115,51",
          planets: [
            {
              r: minSide * 0.04,
              angle: rand(0, Math.PI * 2),
              speed: 0.03,
              size: 2,
              color: "#D4AF37",
            },
            {
              r: minSide * 0.066,
              angle: rand(0, Math.PI * 2),
              speed: 0.017,
              size: 2.4,
              color: "#E8C96A",
            },
          ],
        },
        {
          fx: 0.45,
          fy: 0.62,
          sun: "#D4AF37",
          glow: "212,175,55",
          planets: [
            {
              r: minSide * 0.035,
              angle: rand(0, Math.PI * 2),
              speed: 0.036,
              size: 1.8,
              color: "#D4AF37",
            },
          ],
        },
      ];
      auroras = [
        {
          fx: 0.28,
          fy: 0.22,
          r: 0.58,
          color: "212,175,55",
          phase: 0,
          speed: 0.011,
          base: 0.17,
        },
        {
          fx: 0.76,
          fy: 0.58,
          r: 0.62,
          color: "184,115,51",
          phase: 2.1,
          speed: -0.014,
          base: 0.15,
        },
        {
          fx: 0.55,
          fy: 0.86,
          r: 0.5,
          color: "212,175,55",
          phase: 4,
          speed: 0.017,
          base: 0.15,
        },
        {
          fx: 0.88,
          fy: 0.14,
          r: 0.4,
          color: "205,146,89",
          phase: 1.2,
          speed: -0.009,
          base: 0.12,
        },
        {
          fx: 0.12,
          fy: 0.55,
          r: 0.46,
          color: "156,124,36",
          phase: 3,
          speed: 0.013,
          base: 0.12,
        },
      ];
      cluster = Array.from(
        { length: Math.min(520, Math.round(minSide * 1.3)) },
        () => {
          const radius = Math.pow(Math.random(), 1.7) * minSide * 0.47;
          return {
            angle: rand(0, Math.PI * 2),
            radius,
            size: rand(0.4, 2) * (1 - (radius / (minSide * 0.55)) * 0.4),
            alpha: rand(0.05, 0.4),
            phase: rand(0, Math.PI * 2),
            drift: rand(0, Math.PI * 2),
            driftSpeed: rand(0.0012, 0.0034) * (Math.random() < 0.5 ? 1 : -1),
            color: Math.random() < 0.5 ? "#E8C96A" : "#B87333",
          };
        },
      );
      band = Array.from(
        { length: Math.min(360, Math.round(minSide * 0.9)) },
        () => {
          const t = Math.random();
          const along = t * 1.4 - 0.2;
          const spread = (Math.random() - 0.5) * 0.26;
          return {
            x: (along + spread * 0.6) * width,
            y: (along * 0.7 + 0.05 + spread) * height,
            radius: rand(0.3, 1.2),
            alpha: rand(0.04, 0.26),
          };
        },
      );
    };

    const draw = () => {
      targetX += (mouseX - targetX) * 0.045;
      targetY += (mouseY - targetY) * 0.045;
      const now = performance.now() * 0.001;
      const minSide = Math.min(width, height);
      ctx.clearRect(0, 0, width, height);
      ctx.globalCompositeOperation = "source-over";

      const base = ctx.createLinearGradient(0, 0, width, height);
      base.addColorStop(0, variant === "deep" ? "#0B0B0F" : "#14110E");
      base.addColorStop(0.55, "#100D0A");
      base.addColorStop(1, variant === "constellation" ? "#1C1A17" : "#100B08");
      ctx.fillStyle = base;
      ctx.fillRect(0, 0, width, height);

      ctx.globalCompositeOperation = "lighter";

      for (const aurora of auroras) {
        if (!reducedMotion) aurora.phase += aurora.speed;
        const cx =
          aurora.fx * width +
          Math.sin(aurora.phase) * width * 0.05 +
          targetX * 1.4;
        const cy =
          aurora.fy * height +
          Math.cos(aurora.phase * 0.8) * height * 0.05 +
          targetY * 1.4;
        const radius =
          aurora.r * minSide * (0.9 + Math.sin(aurora.phase * 1.3) * 0.12);
        const alpha =
          aurora.base * (0.72 + Math.sin(aurora.phase * 1.1) * 0.34);
        const gradient = ctx.createRadialGradient(cx, cy, 0, cx, cy, radius);
        gradient.addColorStop(
          0,
          `rgba(${aurora.color},${Math.max(0, alpha).toFixed(3)})`,
        );
        gradient.addColorStop(1, `rgba(${aurora.color},0)`);
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, width, height);
      }

      for (const particle of band) {
        ctx.globalAlpha = particle.alpha;
        ctx.fillStyle = "#9C7C24";
        ctx.beginPath();
        ctx.arc(
          particle.x + targetX * 0.6,
          particle.y + targetY * 0.6,
          particle.radius,
          0,
          Math.PI * 2,
        );
        ctx.fill();
      }
      ctx.globalAlpha = 1;

      for (const galaxy of galaxies) {
        if (!reducedMotion) galaxy.rotation += galaxy.spin;
        const cx = galaxy.fx * width + targetX * 2.4;
        const cy = galaxy.fy * height + targetY * 2.4;
        const cos = Math.cos(galaxy.rotationAngle);
        const sin = Math.sin(galaxy.rotationAngle);
        const core = ctx.createRadialGradient(
          cx,
          cy,
          0,
          cx,
          cy,
          galaxy.radius * 0.62,
        );
        core.addColorStop(0, `rgba(${galaxy.colorA},0.5)`);
        core.addColorStop(0.4, `rgba(${galaxy.colorA},0.18)`);
        core.addColorStop(1, `rgba(${galaxy.colorA},0)`);
        ctx.fillStyle = core;
        ctx.beginPath();
        ctx.arc(cx, cy, galaxy.radius * 0.62, 0, Math.PI * 2);
        ctx.fill();

        for (const point of galaxy.halo) {
          const angle = point.angle + galaxy.rotation * 0.5;
          const lx = Math.cos(angle) * point.r;
          const ly = Math.sin(angle) * point.r * galaxy.tilt;
          ctx.globalAlpha = point.alpha;
          ctx.fillStyle = `rgba(${point.color},1)`;
          ctx.beginPath();
          ctx.arc(
            cx + lx * cos - ly * sin,
            cy + lx * sin + ly * cos,
            point.size,
            0,
            Math.PI * 2,
          );
          ctx.fill();
        }

        for (const point of galaxy.points) {
          const angle = point.angle + galaxy.rotation;
          const lx = Math.cos(angle) * point.r;
          const ly = Math.sin(angle) * point.r * galaxy.tilt;
          ctx.globalAlpha = point.twinkle
            ? Math.max(
                0,
                point.alpha * (0.45 + 0.55 * Math.sin(now * 4 + point.phase)),
              )
            : point.alpha;
          ctx.fillStyle = `rgba(${point.color},1)`;
          ctx.beginPath();
          ctx.arc(
            cx + lx * cos - ly * sin,
            cy + lx * sin + ly * cos,
            point.size,
            0,
            Math.PI * 2,
          );
          ctx.fill();
        }
        ctx.globalAlpha = 1;
      }

      const clusterX = width * 0.5 + targetX * 1.2;
      const clusterY = height * 0.5 + targetY * 1.2;
      const breathe = 0.86 + Math.sin(now * 0.9) * 0.14;
      const clusterGlow = ctx.createRadialGradient(
        clusterX,
        clusterY,
        0,
        clusterX,
        clusterY,
        minSide * 0.52 * breathe,
      );
      clusterGlow.addColorStop(0, "rgba(212,175,55,0.32)");
      clusterGlow.addColorStop(0.34, "rgba(232,201,106,0.16)");
      clusterGlow.addColorStop(0.7, "rgba(184,115,51,0.05)");
      clusterGlow.addColorStop(1, "rgba(184,115,51,0)");
      ctx.fillStyle = clusterGlow;
      ctx.fillRect(0, 0, width, height);

      for (const particle of cluster) {
        if (!reducedMotion) particle.drift += particle.driftSpeed;
        const angle = particle.angle + particle.drift;
        const x = clusterX + Math.cos(angle) * particle.radius;
        const y = clusterY + Math.sin(angle) * particle.radius * 0.72;
        ctx.globalAlpha =
          particle.alpha *
          0.95 *
          (0.5 + 0.5 * Math.sin(now * 2.4 + particle.phase));
        ctx.fillStyle = particle.color;
        ctx.beginPath();
        ctx.arc(x, y, particle.size, 0, Math.PI * 2);
        ctx.fill();
      }
      ctx.globalAlpha = 1;

      for (const system of systems) {
        const cx = system.fx * width + targetX * 3.2;
        const cy = system.fy * height + targetY * 3.2;
        const glow = ctx.createRadialGradient(cx, cy, 0, cx, cy, 26);
        glow.addColorStop(0, `rgba(${system.glow},0.45)`);
        glow.addColorStop(1, `rgba(${system.glow},0)`);
        ctx.fillStyle = glow;
        ctx.beginPath();
        ctx.arc(cx, cy, 26, 0, Math.PI * 2);
        ctx.fill();
        ctx.fillStyle = system.sun;
        ctx.beginPath();
        ctx.arc(cx, cy, 3.2, 0, Math.PI * 2);
        ctx.fill();

        for (const planet of system.planets) {
          if (!reducedMotion) planet.angle += planet.speed;
          ctx.strokeStyle = "rgba(212,175,55,0.18)";
          ctx.lineWidth = 0.7;
          ctx.beginPath();
          ctx.ellipse(cx, cy, planet.r, planet.r * 0.46, 0, 0, Math.PI * 2);
          ctx.stroke();
          ctx.fillStyle = planet.color;
          ctx.beginPath();
          ctx.arc(
            cx + Math.cos(planet.angle) * planet.r,
            cy + Math.sin(planet.angle) * planet.r * 0.46,
            planet.size,
            0,
            Math.PI * 2,
          );
          ctx.fill();
        }
      }

      for (const star of stars) {
        if (!reducedMotion) {
          star.a += star.twinkle * star.dir;
          if (star.a > 1) {
            star.a = 1;
            star.dir = -1;
          }
          if (star.a < 0.12) {
            star.a = 0.12;
            star.dir = 1;
          }
        }
        ctx.globalAlpha = star.a;
        ctx.fillStyle = star.color;
        ctx.beginPath();
        ctx.arc(
          star.x + targetX * (star.radius * 1.1),
          star.y + targetY * (star.radius * 1.1),
          star.radius,
          0,
          Math.PI * 2,
        );
        ctx.fill();
      }

      if (variant === "constellation") {
        ctx.globalAlpha = 1;
        for (const node of nodes) {
          if (!reducedMotion) {
            node.x += node.vx;
            node.y += node.vy;
            if (node.x < 0 || node.x > width) node.vx *= -1;
            if (node.y < 0 || node.y > height) node.vy *= -1;
          }
        }

        for (let i = 0; i < nodes.length; i += 1) {
          const node = nodes[i];
          for (let j = i + 1; j < nodes.length; j += 1) {
            const other = nodes[j];
            const dx = node.x - other.x;
            const dy = node.y - other.y;
            const dist = Math.sqrt(dx * dx + dy * dy);
            if (dist < 138) {
              ctx.globalAlpha = (1 - dist / 138) * 0.55;
              ctx.strokeStyle = i % 2 ? "#E8C96A" : "#B87333";
              ctx.lineWidth = 0.7;
              ctx.beginPath();
              ctx.moveTo(node.x + targetX, node.y + targetY);
              ctx.lineTo(other.x + targetX, other.y + targetY);
              ctx.stroke();
            }
          }
        }

        ctx.globalAlpha = 1;
        for (const node of nodes) {
          ctx.fillStyle = "#D4AF37";
          ctx.beginPath();
          ctx.arc(node.x + targetX, node.y + targetY, 1.7, 0, Math.PI * 2);
          ctx.fill();
        }
      } else {
        for (const particle of dust) {
          if (!reducedMotion) {
            particle.y -= particle.vy;
            particle.x += particle.vx;
            if (particle.y < -4) {
              particle.y = height + 4;
              particle.x = rand(0, width);
            }
          }
          ctx.globalAlpha = particle.alpha;
          ctx.fillStyle = "#B87333";
          ctx.beginPath();
          ctx.arc(
            particle.x + targetX,
            particle.y + targetY,
            particle.radius,
            0,
            Math.PI * 2,
          );
          ctx.fill();
        }
      }

      ctx.globalAlpha = 1;

      if (!reducedMotion) {
        shootingTimer -= 1;
        if (shootingTimer <= 0 && !shootingStar) {
          shootingStar = {
            x: rand(0, width * 0.6),
            y: rand(0, height * 0.35),
            speed: rand(6, 10),
            length: rand(80, 170),
            life: 1,
          };
          shootingTimer = rand(260, 560);
        }
      }

      if (shootingStar) {
        const angle = Math.PI * 0.18;
        if (!reducedMotion) {
          shootingStar.x += Math.cos(angle) * shootingStar.speed;
          shootingStar.y += Math.sin(angle) * shootingStar.speed;
          shootingStar.life -= 0.012;
        }
        const endX = shootingStar.x - Math.cos(angle) * shootingStar.length;
        const endY = shootingStar.y - Math.sin(angle) * shootingStar.length;
        const gradient = ctx.createLinearGradient(
          shootingStar.x,
          shootingStar.y,
          endX,
          endY,
        );
        gradient.addColorStop(
          0,
          `rgba(212,175,55,${Math.max(0, shootingStar.life * 0.8)})`,
        );
        gradient.addColorStop(1, "rgba(212,175,55,0)");
        ctx.strokeStyle = gradient;
        ctx.lineWidth = 1.6;
        ctx.beginPath();
        ctx.moveTo(shootingStar.x, shootingStar.y);
        ctx.lineTo(endX, endY);
        ctx.stroke();
        if (
          shootingStar.life <= 0 ||
          shootingStar.x > width ||
          shootingStar.y > height
        ) {
          shootingStar = null;
        }
      }

      if (!reducedMotion) raf = requestAnimationFrame(draw);
    };

    const onMouseMove = (event) => {
      const rect = host.getBoundingClientRect();
      mouseX = ((event.clientX - rect.left) / rect.width - 0.5) * 38;
      mouseY = ((event.clientY - rect.top) / rect.height - 0.5) * 38;
    };

    const onMouseLeave = () => {
      mouseX = 0;
      mouseY = 0;
    };

    build();
    draw();
    const resizeObserver = new ResizeObserver(build);
    resizeObserver.observe(host);
    host.addEventListener("mousemove", onMouseMove, { passive: true });
    host.addEventListener("mouseleave", onMouseLeave);

    return () => {
      cancelAnimationFrame(raf);
      resizeObserver.disconnect();
      host.removeEventListener("mousemove", onMouseMove);
      host.removeEventListener("mouseleave", onMouseLeave);
    };
  }, [canvasRef, hostRef, variant]);
}

function HomeNav() {
  return (
    <nav className="fixed top-0 left-0 right-0 z-50 flex items-center justify-between gap-4 px-5 py-4 md:px-10 lg:px-16 home-nav-glass">
      <HomeLogoMark size="md" />
      <div className="hidden items-center gap-8 text-sm font-semibold text-[#A89F8C] md:flex">
        <a href="/assistant" className="home-link">
          Assistente
        </a>
        <a href="/websites" className="home-link">
          Websites
        </a>
        <a href="#precos" className="home-link">
          Preços
        </a>
      </div>
      <a href="/contacto" className="home-gold-button text-sm">
        Falar connosco
      </a>
    </nav>
  );
}

function HeroOrbitCard({ type }) {
  const isAssistant = type === "assistant";
  return (
    <div
      className="flex items-center gap-3 whitespace-nowrap rounded-2xl border bg-[#1C1A17]/85 px-4 py-3 shadow-[0_8px_26px_rgba(0,0,0,0.5)] backdrop-blur-xl"
      style={{
        borderColor: isAssistant
          ? "rgba(184,115,51,0.36)"
          : "rgba(212,175,55,0.36)",
      }}
    >
      <ProductOrbGlyph tone={isAssistant ? "assistant" : "websites"} />
      <div>
        <div className="home-display text-sm font-bold leading-tight text-[#E9E1D0]">
          {isAssistant ? "Assistant" : "Websites"}
        </div>
        <div className="text-xs text-[#A89F8C]">
          {isAssistant ? "Responde 24/7" : "Presença online"}
        </div>
      </div>
    </div>
  );
}

function HeroOrbitalVisual({ variant }) {
  if (variant !== "orbital") {
    return (
      <div className="mt-12 flex flex-wrap justify-center gap-4 home-word-delay-4">
        <div className="home-float">
          <HeroOrbitCard type="assistant" />
        </div>
        <div className="home-float-delay">
          <HeroOrbitCard type="websites" />
        </div>
      </div>
    );
  }

  return (
    <div className="relative mx-auto flex min-h-[390px] items-center justify-center md:min-h-[500px] home-word-delay-3">
      <div className="absolute h-[280px] w-[280px] rounded-full border border-dashed border-[#B87333]/35 motion-safe:animate-[spin_26s_linear_infinite] md:h-[320px] md:w-[320px]">
        <div className="absolute -top-7 left-1/2 -translate-x-1/2 motion-safe:animate-[spin_26s_linear_infinite_reverse]">
          <HeroOrbitCard type="assistant" />
        </div>
      </div>
      <div className="absolute h-[360px] w-[360px] rounded-full border border-dashed border-[#D4AF37]/30 motion-safe:animate-[spin_40s_linear_infinite_reverse] md:h-[470px] md:w-[470px]">
        <div className="absolute -bottom-7 left-1/2 -translate-x-1/2 motion-safe:animate-[spin_40s_linear_infinite]">
          <HeroOrbitCard type="websites" />
        </div>
      </div>
      <div className="absolute h-32 w-32 rounded-full border border-[#D4AF37]/40 home-ring" />
      <div className="absolute h-32 w-32 rounded-full border border-[#B87333]/40 home-ring-delay" />
      <div className="relative flex h-32 w-32 flex-col items-center justify-center rounded-full text-center home-core">
        <span className="home-display text-base font-bold text-[#FFFDF6]">
          Captixy
        </span>
        <span className="mt-1 text-[10px] tracking-[0.18em] text-[#FFFDF6]/80">
          CORE
        </span>
      </div>
    </div>
  );
}

function HomeHero() {
  const variant = "constellation";
  const canvasRef = useHomeRef(null);
  const heroRef = useHomeRef(null);
  useCosmicCanvas(canvasRef, heroRef, variant);

  const scrollProducts = () =>
    document.getElementById("produtos")?.scrollIntoView({ behavior: "smooth" });
  const centered = variant !== "orbital";

  return (
    <section
      ref={heroRef}
      className="relative flex min-h-[100svh] flex-col items-center justify-center overflow-hidden px-5 pb-24 pt-32 md:px-10 lg:px-16"
    >
      <canvas
        ref={canvasRef}
        className="absolute inset-0 block h-full w-full"
        aria-hidden="true"
      />
      <div className="absolute left-[8%] top-[-12%] h-[46vw] max-h-[680px] w-[46vw] max-w-[680px] rounded-full bg-[radial-gradient(circle,rgba(212,175,55,0.34),transparent_62%)] blur-[44px] home-nebula pointer-events-none" />
      <div className="absolute bottom-[-18%] right-[4%] h-[48vw] max-h-[720px] w-[48vw] max-w-[720px] rounded-full bg-[radial-gradient(circle,rgba(184,115,51,0.28),transparent_62%)] blur-[50px] home-nebula-reverse pointer-events-none" />

      <div
        className={`relative z-[2] w-full max-w-6xl ${centered ? "text-center" : "grid items-center gap-10 lg:grid-cols-[1.05fr_0.95fr]"}`}
      >
        <div
          className={
            centered ? "mx-auto flex max-w-4xl flex-col items-center" : ""
          }
        >
          <h1
            className={`home-display font-bold leading-[1.02] tracking-[-0.04em] text-[#F5F1E6] ${centered ? "text-[clamp(42px,7vw,84px)]" : "text-[clamp(40px,6vw,72px)]"}`}
          >
            <span className="block home-word-delay-1">Capta, organiza e</span>
            <span className="block bg-[linear-gradient(110deg,#D4AF37,#B87333)] bg-clip-text text-transparent home-word-delay-2">
              converte mais clientes.
            </span>
          </h1>

          <p
            className={`mt-7 text-base leading-[1.7] text-[#C4BDA8] md:text-lg ${centered ? "mx-auto max-w-2xl" : "max-w-xl"} home-word-delay-3`}
          >
            A Captixy reúne dois produtos que trabalham em sintonia, o{" "}
            <strong className="font-semibold text-[#F8F3E8]">
              Assistente Virtual
            </strong>{" "}
            e os{" "}
            <strong className="font-semibold text-[#F8F3E8]">
              Websites profissionais
            </strong>
            , para o teu negócio captar e converter clientes 24 horas por dia.
          </p>

          <div
            className={`mt-9 flex flex-wrap gap-4 ${centered ? "justify-center" : ""} home-word-delay-4`}
          >
            <button
              type="button"
              onClick={scrollProducts}
              className="home-gold-button text-base"
            >
              Ver os produtos <HomeArrow />
            </button>
            <a
              href="/contacto"
              className="inline-flex items-center gap-2 rounded-full border border-white/25 bg-white/[0.06] px-7 py-4 text-base font-semibold text-[#F5F1E6] backdrop-blur-lg transition-colors duration-200 hover:border-white/40 hover:bg-white/[0.12] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#E8C96A]"
            >
              Falar connosco
            </a>
          </div>

          {!centered && (
            <div className="mt-10 flex flex-wrap gap-6 text-sm text-[#A89F8C] home-word-delay-5">
              {[
                ["Websites profissionais", HOME_GOLD],
                ["Assistente 24/7", HOME_AMBER],
                ["Setup em dias", "#E8C96A"],
              ].map(([text, color]) => (
                <span key={text} className="inline-flex items-center gap-2">
                  <span
                    className="h-2 w-2 rounded-full"
                    style={{ background: color }}
                  />
                  {text}
                </span>
              ))}
            </div>
          )}
        </div>

        <HeroOrbitalVisual variant={variant} />
      </div>

      <div className="absolute bottom-7 left-1/2 z-[2] -translate-x-1/2">
        <div className="flex flex-col items-center gap-2 text-[11px] uppercase tracking-[0.16em] text-[#837C6D] home-float">
          <span>Explorar</span>
          <span className="h-8 w-px bg-gradient-to-b from-[#837C6D] to-transparent" />
        </div>
      </div>
    </section>
  );
}

function SectionHeader({ eyebrow, title, body }) {
  return (
    <div className="mx-auto mb-14 max-w-3xl text-center home-reveal">
      <div className="mb-4 text-xs font-bold uppercase tracking-[0.16em] text-[#D4AF37]">
        {eyebrow}
      </div>
      <h2 className="home-display text-[clamp(30px,4.2vw,52px)] font-bold leading-[1.08] tracking-[-0.03em] text-[#E9E1D0]">
        {title}
      </h2>
      {body && (
        <p className="mx-auto mt-5 max-w-xl text-base leading-[1.7] text-[#A89F8C] md:text-lg">
          {body}
        </p>
      )}
    </div>
  );
}

function HomeProductCard({ tone, eyebrow, title, body, bullets, href, cta }) {
  const isAssistant = tone === "assistant";
  return (
    <a
      href={href}
      className="group relative block overflow-hidden rounded-[1.75rem] border p-7 shadow-[0_12px_40px_rgba(0,0,0,0.35)] transition-all duration-300 hover:-translate-y-1.5 hover:shadow-[0_24px_56px_rgba(0,0,0,0.55)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#D4AF37] md:p-10 home-reveal"
      style={{
        background: isAssistant
          ? "linear-gradient(165deg,#221D17,#16130F)"
          : "linear-gradient(165deg,#1E1C18,#141210)",
        borderColor: isAssistant
          ? "rgba(184,115,51,0.32)"
          : "rgba(212,175,55,0.3)",
      }}
    >
      <div
        className="absolute -right-10 -top-10 h-52 w-52 rounded-full blur-2xl transition-opacity duration-300 group-hover:opacity-90"
        style={{
          background: isAssistant
            ? "radial-gradient(circle,rgba(184,115,51,0.22),transparent 65%)"
            : "radial-gradient(circle,rgba(212,175,55,0.2),transparent 65%)",
        }}
      />
      <div className="relative mb-6 flex items-center gap-4">
        <ProductOrbGlyph tone={tone} size="lg" />
        <span
          className="text-xs font-bold uppercase tracking-[0.12em]"
          style={{ color: isAssistant ? "#CD9259" : "#D4AF37" }}
        >
          {eyebrow}
        </span>
      </div>
      <h3 className="home-display relative mb-4 text-[clamp(24px,2.6vw,32px)] font-bold leading-[1.12] tracking-[-0.02em] text-[#E9E1D0]">
        {title}
      </h3>
      <p className="relative mb-7 text-base leading-[1.7] text-[#A89F8C]">
        {body}
      </p>
      <div className="relative mb-8 flex flex-col gap-3">
        {bullets.map((bullet) => (
          <div
            key={bullet}
            className="flex items-start gap-3 text-[15px] leading-snug text-[#C4BDA8]"
          >
            <HomeCheck
              className="mt-0.5 h-4 w-4 shrink-0"
              style={{ color: isAssistant ? HOME_AMBER : HOME_GOLD }}
            />
            <span>{bullet}</span>
          </div>
        ))}
      </div>
      <span
        className="relative inline-flex items-center gap-2 home-display text-sm font-bold transition-colors group-hover:text-[#E9E1D0]"
        style={{ color: isAssistant ? "#CD9259" : "#D4AF37" }}
      >
        {cta}{" "}
        <HomeArrow className="w-4 h-4 transition-transform duration-200 group-hover:translate-x-1" />
      </span>
    </a>
  );
}

function ProductsSection() {
  return (
    <section
      id="produtos"
      className="relative mx-auto max-w-7xl px-5 py-24 md:px-8 md:py-32"
    >
      <SectionHeader
        eyebrow="Dois produtos, um sistema"
        title="Tudo o que precisas para crescer."
      />
      <div className="grid gap-6 md:grid-cols-2">
        <HomeProductCard
          tone="assistant"
          eyebrow="Captixy Assistant"
          title="Um assistente virtual que nunca dorme."
          body="Responde, qualifica e organiza contactos automaticamente no teu site. Cada lead é tratada ao instante, mesmo fora do horário."
          bullets={[
            "Respostas instantâneas, 24 horas por dia",
            "Qualifica e organiza leads",
            "Link público, QR code ou widget no site",
            "Fala a língua do teu cliente",
          ]}
          href="/assistant"
          cta="Conhecer o Assistant"
        />
        <HomeProductCard
          tone="websites"
          eyebrow="Captixy Websites"
          title="Websites profissionais para seres encontrado."
          body="Sites rápidos, bonitos e optimizados para Google, prontos em dias, não meses. A tua presença online, à medida."
          bullets={[
            "Design à medida do teu negócio",
            "Optimizado para Google",
            "Pronto em poucos dias",
            "Integração com o Assistente Virtual",
          ]}
          href="/websites"
          cta="Conhecer os Websites"
        />
      </div>
    </section>
  );
}

function StepsSection() {
  const steps = [
    [
      "01",
      "Capta",
      "O teu website atrai visitantes no Google, nas redes e por recomendação.",
    ],
    [
      "02",
      "Responde",
      "O Assistente responde e qualifica cada contacto ao instante.",
    ],
    [
      "03",
      "Organiza",
      "As leads chegam organizadas, com contexto e próximo passo claro.",
    ],
    ["04", "Converte", "A tua equipa foca-se no que importa: fechar negócio."],
  ];
  return (
    <section className="relative mx-auto max-w-6xl px-5 py-20 md:px-8 md:py-28">
      <SectionHeader
        eyebrow="Melhores juntos"
        title="Dois produtos, uma só estratégia."
        body="O Website capta. O Assistente converte. Juntos, transformam visitantes em clientes sem perder contactos pelo caminho."
      />
      <div className="relative grid gap-8 sm:grid-cols-2 lg:grid-cols-4">
        <div className="absolute left-[8%] right-[8%] top-9 hidden h-px bg-gradient-to-r from-transparent via-[#B87333]/55 to-transparent lg:block" />
        {steps.map(([number, title, body]) => (
          <div key={number} className="relative z-10 text-center home-reveal">
            <div className="home-display mx-auto mb-5 flex h-[72px] w-[72px] items-center justify-center rounded-full border border-[#D4AF37]/45 bg-[#1F1C17] text-2xl font-bold text-[#D4AF37] shadow-[0_6px_18px_rgba(0,0,0,0.45)]">
              {number}
            </div>
            <h3 className="home-display mb-2 text-xl font-bold text-[#E9E1D0]">
              {title}
            </h3>
            <p className="text-sm leading-[1.65] text-[#A89F8C]">{body}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

function PriceCard({
  featured,
  eyebrow,
  price,
  sub,
  bullets,
  href,
  cta,
  tone,
}) {
  const isAssistant = tone === "assistant";
  return (
    <div
      className={`relative flex flex-col rounded-[1.5rem] border p-7 shadow-[0_10px_34px_rgba(0,0,0,0.35)] home-reveal ${featured ? "md:-translate-y-3" : ""}`}
      style={{
        background: featured
          ? "linear-gradient(170deg,#2A2620,#16130F)"
          : "#1A1815",
        borderColor: featured
          ? "rgba(212,175,55,0.55)"
          : isAssistant
            ? "rgba(184,115,51,0.3)"
            : "rgba(212,175,55,0.26)",
        boxShadow: featured
          ? "0 22px 56px rgba(0,0,0,0.55), 0 0 30px -6px rgba(212,175,55,0.22)"
          : undefined,
      }}
    >
      {featured && (
        <div className="absolute -top-3 left-1/2 -translate-x-1/2 rounded-full bg-[linear-gradient(135deg,#D4AF37,#E8C96A)] px-4 py-1.5 text-[11px] font-bold uppercase tracking-[0.08em] text-[#0B0B0F]">
          Recomendado
        </div>
      )}
      <div
        className="mb-4 text-xs font-bold uppercase tracking-[0.12em]"
        style={{ color: isAssistant ? "#CD9259" : "#D4AF37" }}
      >
        {eyebrow}
      </div>
      <div
        className="mb-2 home-display text-[clamp(32px,4vw,44px)] font-bold leading-tight tracking-[-0.03em]"
        style={{
          color: featured || !isAssistant ? "transparent" : HOME_INK,
          background:
            featured || !isAssistant
              ? "linear-gradient(110deg,#D4AF37,#B87333)"
              : undefined,
          WebkitBackgroundClip: featured || !isAssistant ? "text" : undefined,
          backgroundClip: featured || !isAssistant ? "text" : undefined,
        }}
      >
        {price}
      </div>
      <div className="mb-7 text-sm text-[#A89F8C]">{sub}</div>
      <div className="mb-8 flex flex-1 flex-col gap-3">
        {bullets.map((bullet) => (
          <div
            key={bullet}
            className="flex gap-3 text-sm leading-snug text-[#C4BDA8]"
          >
            <HomeCheck
              className="h-4 w-4 shrink-0"
              style={{ color: isAssistant ? HOME_AMBER : HOME_GOLD }}
            />
            <span>{bullet}</span>
          </div>
        ))}
      </div>
      <a
        href={href}
        className={
          featured
            ? "home-gold-button justify-center text-sm"
            : "rounded-full border border-[#D4AF37]/45 px-5 py-3 text-center text-sm font-bold text-[#D4AF37] transition-colors duration-200 hover:bg-[#D4AF37]/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#D4AF37]"
        }
      >
        {cta}
      </a>
    </div>
  );
}

function PricingSection() {
  return (
    <section
      id="precos"
      className="relative mx-auto max-w-7xl px-5 py-20 md:px-8 md:py-28"
    >
      <SectionHeader
        eyebrow="Preços transparentes"
        title="Começa por onde fizer mais sentido."
      />
      <div className="grid gap-6 lg:grid-cols-3 lg:items-stretch">
        <PriceCard
          eyebrow="Captixy Websites"
          price="Presença online à medida"
          sub="Projecto único, com opções detalhadas na página do produto"
          bullets={[
            "Site profissional à medida",
            "Optimizado para Google",
            "Pronto em poucos dias",
          ]}
          href="/websites"
          cta="Ver Websites"
          tone="websites"
        />
        <PriceCard
          featured
          eyebrow="Captixy Completo"
          price="Website + Assistente"
          sub="A solução completa, em sintonia"
          bullets={[
            "Website profissional incluído",
            "Assistente virtual 24/7",
            "Captação e conversão num só sistema",
          ]}
          href="/contacto"
          cta="Falar connosco"
          tone="websites"
        />
        <PriceCard
          eyebrow="Captixy Assistant"
          price="Planos mensais"
          sub="À medida do teu volume de contactos"
          bullets={[
            "Assistente sempre disponível",
            "Site e links públicos integrados",
            "Sem permanência obrigatória",
          ]}
          href="/assistant"
          cta="Ver Assistant"
          tone="assistant"
        />
      </div>
    </section>
  );
}

function FinalCTA() {
  const scrollProducts = () =>
    document.getElementById("produtos")?.scrollIntoView({ behavior: "smooth" });
  return (
    <section className="relative px-5 pb-24 pt-8 md:px-8">
      <div className="relative mx-auto max-w-6xl overflow-hidden rounded-[2rem] border border-[#E8C96A]/45 bg-[linear-gradient(150deg,#1F1A14,#0B0B0F)] px-7 py-16 text-center shadow-[0_24px_60px_rgba(20,12,4,0.45)] md:px-16 md:py-20 home-reveal">
        <div className="absolute left-1/2 top-[-30%] h-[520px] w-[520px] -translate-x-1/2 rounded-full bg-[radial-gradient(circle,rgba(212,175,55,0.42),transparent_60%)] blur-[50px] pointer-events-none" />
        <div className="relative">
          <h2 className="home-display text-[clamp(30px,4.4vw,54px)] font-bold leading-[1.06] tracking-[-0.03em] text-[#FDFAF2]">
            Pronto para transformar o teu
            <br className="hidden sm:block" /> negócio digital?
          </h2>
          <p className="mx-auto mt-5 max-w-xl text-base leading-[1.7] text-[#FDFAF2]/80 md:text-lg">
            Falamos contigo sobre o que faz mais sentido para o teu negócio, sem
            compromisso.
          </p>
          <div className="mt-9 flex flex-wrap justify-center gap-4">
            <a href="/contacto" className="home-gold-button text-base">
              Falar connosco <HomeArrow />
            </a>
            <button
              type="button"
              onClick={scrollProducts}
              className="inline-flex items-center gap-2 rounded-full border border-[#FDFAF2]/40 bg-[#FDFAF2]/10 px-8 py-4 text-base font-semibold text-[#FDFAF2] transition-colors duration-200 hover:bg-[#FDFAF2]/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#E8C96A]"
            >
              Ver os produtos
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

function HomeFooter() {
  return (
    <footer className="relative border-t border-[#E9E1D0]/10 px-5 pb-10 pt-16 md:px-8">
      <div className="mx-auto grid max-w-7xl gap-10 sm:grid-cols-2 lg:grid-cols-[1.4fr_1fr_1fr_1fr]">
        <div>
          <HomeLogoMark size="md" />
          <p className="mt-5 max-w-xs text-sm leading-[1.7] text-[#A89F8C]">
            A plataforma que ajuda o teu negócio a captar, organizar e converter
            mais clientes.
          </p>
        </div>
        <FooterColumn
          title="Produtos"
          links={[
            ["Captixy Assistant", "/assistant"],
            ["Captixy Websites", "/websites"],
            ["Preços", "#precos"],
          ]}
        />
        <FooterColumn
          title="Empresa"
          links={[
            ["Sobre", "/sobre"],
            ["Contacto", "/contacto"],
          ]}
        />
        <FooterColumn
          title="Legal"
          links={[
            ["Termos", "/termos"],
            ["Privacidade", "/privacidade"],
          ]}
        />
      </div>
      <div className="mx-auto mt-12 flex max-w-7xl flex-wrap justify-between gap-4 border-t border-[#E9E1D0]/10 pt-6 text-sm text-[#837C6D]">
        <span>© 2026 Captixy. Todos os direitos reservados.</span>
        <span>Feito em Portugal</span>
      </div>
    </footer>
  );
}

function FooterColumn({ title, links }) {
  return (
    <div>
      <div className="home-display mb-4 text-sm font-bold text-[#E9E1D0]">
        {title}
      </div>
      <div className="flex flex-col gap-3 text-sm text-[#A89F8C]">
        {links.map(([label, href]) => (
          <a
            key={href}
            href={href}
            className="transition-colors duration-200 hover:text-[#D4AF37]"
          >
            {label}
          </a>
        ))}
      </div>
    </div>
  );
}

function HomeApp() {
  return (
    <main
      className="home-cosmic min-h-screen overflow-hidden"
      style={{ background: HOME_PARCHMENT, color: HOME_INK }}
    >
      <HomeNav />
      <HomeHero />
      <ProductsSection />
      <StepsSection />
      <PricingSection />
      <FinalCTA />
      <HomeFooter />
    </main>
  );
}

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