/* global React */
/* Animated cloud architecture diagram for hero */

const { useEffect, useRef, useState } = React;

function HeroDiagram() {
  const [t, setT] = useState(0);
  const rafRef = useRef(0);
  const startRef = useRef(0);

  useEffect(() => {
    const tick = (now) => {
      if (!startRef.current) startRef.current = now;
      setT((now - startRef.current) / 1000);
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, []);

  // Geometry — 600x600 viewBox
  const NODES = {
    git:    { x: 90,  y: 110, label: "git", sub: "main" },
    ci:     { x: 90,  y: 230, label: "ci/cd", sub: "pipeline" },
    iac:    { x: 90,  y: 350, label: "terraform", sub: "plan/apply" },
    secret: { x: 90,  y: 470, label: "vault", sub: "secrets" },

    core:   { x: 300, y: 300, label: "control plane", sub: "policy · iam · audit" },

    aws:    { x: 510, y: 130, label: "AWS", sub: "eu-west-1" },
    azure:  { x: 510, y: 250, label: "Azure", sub: "westeurope" },
    gcp:    { x: 510, y: 370, label: "GCP", sub: "europe-west1" },
    obs:    { x: 510, y: 490, label: "observability", sub: "metrics · logs" },
  };

  const EDGES = [
    ["git", "core"],
    ["ci", "core"],
    ["iac", "core"],
    ["secret", "core"],
    ["core", "aws"],
    ["core", "azure"],
    ["core", "gcp"],
    ["core", "obs"],
  ];

  const nodeBox = (n, w = 130, h = 44) => ({
    x: n.x - w / 2, y: n.y - h / 2, w, h,
    cx: n.x, cy: n.y,
  });

  // helper: build orthogonal-ish path between two nodes
  const path = (a, b) => {
    const ax = a.x, ay = a.y, bx = b.x, by = b.y;
    const midX = (ax + bx) / 2;
    return `M ${ax} ${ay} C ${midX} ${ay}, ${midX} ${by}, ${bx} ${by}`;
  };

  return (
    <div className="hero-diagram">
      <div className="badge"><span className="pulse"></span>multi-cloud · live</div>
      <svg viewBox="0 0 600 600" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
        <defs>
          <linearGradient id="edgeGrad" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor="var(--accent)" stopOpacity="0" />
            <stop offset="40%" stopColor="var(--accent)" stopOpacity="0.95" />
            <stop offset="60%" stopColor="var(--accent)" stopOpacity="0.95" />
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
          </linearGradient>
          <pattern id="dot" width="20" height="20" patternUnits="userSpaceOnUse">
            <circle cx="1" cy="1" r="0.6" fill="var(--ink-4)" opacity="0.35" />
          </pattern>
          <filter id="soft" x="-20%" y="-20%" width="140%" height="140%">
            <feGaussianBlur stdDeviation="0.4" />
          </filter>
        </defs>

        {/* dotted background */}
        <rect width="600" height="600" fill="url(#dot)" />

        {/* edges - base */}
        {EDGES.map(([a, b], i) => (
          <path
            key={"e" + i}
            d={path(NODES[a], NODES[b])}
            stroke="var(--line-strong)"
            strokeWidth="1"
            strokeDasharray="3 4"
            fill="none"
            opacity="0.7"
          />
        ))}

        {/* edges - animated traveling pulses */}
        {EDGES.map(([a, b], i) => {
          const phase = (t * 0.35 + i * 0.18) % 1;
          return (
            <g key={"p" + i}>
              <circle r="3.2" fill="var(--accent)">
                <animateMotion dur={`${3.5 + (i % 3) * 0.6}s`} repeatCount="indefinite" begin={`${-i * 0.4}s`} keyTimes="0;1" keySplines="0.4 0 0.6 1" calcMode="spline" path={path(NODES[a], NODES[b])} />
              </circle>
            </g>
          );
        })}

        {/* nodes */}
        {Object.entries(NODES).map(([key, n]) => {
          const isCore = key === "core";
          const w = isCore ? 168 : 130;
          const h = isCore ? 60 : 44;
          const box = nodeBox(n, w, h);
          return (
            <g key={key} transform={`translate(${box.x} ${box.y})`}>
              <rect
                width={w}
                height={h}
                rx="10"
                fill="var(--bg-elev)"
                stroke={isCore ? "var(--accent)" : "var(--line-strong)"}
                strokeWidth={isCore ? 1.5 : 1}
              />
              {isCore && (
                <rect
                  width={w}
                  height={h}
                  rx="10"
                  fill="none"
                  stroke="var(--accent)"
                  strokeWidth="1"
                  opacity="0.35"
                >
                  <animate attributeName="opacity" values="0.5;0;0.5" dur="3s" repeatCount="indefinite" />
                  <animate attributeName="stroke-width" values="1;4;1" dur="3s" repeatCount="indefinite" />
                </rect>
              )}

              {/* tiny status dot */}
              <circle cx={12} cy={h / 2} r={3} fill="var(--accent)">
                <animate attributeName="opacity" values="1;0.3;1" dur={`${2 + (n.x % 7) * 0.1}s`} repeatCount="indefinite" />
              </circle>

              <text
                x={24}
                y={isCore ? h / 2 - 4 : h / 2 - 2}
                dominantBaseline="middle"
                fontFamily="var(--font-mono)"
                fontSize={isCore ? "13" : "11.5"}
                fill="var(--ink)"
                style={{ letterSpacing: "0.02em" }}
              >
                {n.label}
              </text>
              <text
                x={24}
                y={isCore ? h / 2 + 12 : h / 2 + 11}
                dominantBaseline="middle"
                fontFamily="var(--font-mono)"
                fontSize={isCore ? "10" : "9.5"}
                fill="var(--ink-4)"
                style={{ letterSpacing: "0.04em" }}
              >
                {n.sub}
              </text>
            </g>
          );
        })}

        {/* group labels */}
        <text x="90" y="60" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9.5" fill="var(--ink-4)" style={{ letterSpacing: "0.18em" }}>
          DEV / PIPELINE
        </text>
        <text x="300" y="60" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9.5" fill="var(--ink-4)" style={{ letterSpacing: "0.18em" }}>
          CONTROL PLANE
        </text>
        <text x="510" y="60" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9.5" fill="var(--ink-4)" style={{ letterSpacing: "0.18em" }}>
          MULTI-CLOUD
        </text>

        {/* group dividers */}
        <line x1="190" y1="80" x2="190" y2="540" stroke="var(--line)" strokeDasharray="2 4" />
        <line x1="410" y1="80" x2="410" y2="540" stroke="var(--line)" strokeDasharray="2 4" />

        {/* corner brackets */}
        {[[14, 14, 1, 1], [586, 14, -1, 1], [14, 586, 1, -1], [586, 586, -1, -1]].map(([x, y, sx, sy], i) => (
          <g key={"c" + i} stroke="var(--line-strong)" strokeWidth="1" fill="none">
            <line x1={x} y1={y} x2={x + 14 * sx} y2={y} />
            <line x1={x} y1={y} x2={x} y2={y + 14 * sy} />
          </g>
        ))}
      </svg>
    </div>
  );
}

window.HeroDiagram = HeroDiagram;
