/* Hero section */

/* ============================================================
   Live mesh telemetry — reads window.__rozumMesh on rAF and
   renders the changing XYZ/coords block in the corner.
   ============================================================ */
function MeshTelemetry() {
  const [t, setT] = React.useState({
    rotX: 0, rotY: 0, rotZ: 0, breath: 0, particles: 0, edges: 0, verts: 0,
    fps: 60, packets: 0,
  });
  const lastFrame = React.useRef(performance.now());
  const fpsRef = React.useRef(60);

  React.useEffect(() => {
    let raf;
    let pkt = 0;
    const tick = () => {
      const m = window.__rozumMesh && window.__rozumMesh.telemetry;
      const now = performance.now();
      const dtMs = now - lastFrame.current;
      lastFrame.current = now;
      fpsRef.current = fpsRef.current * 0.92 + (1000 / Math.max(dtMs, 1)) * 0.08;
      pkt += Math.random() < 0.4 ? 1 : 0;
      if (m) {
        setT({
          rotX: m.rotX || 0,
          rotY: m.rotY || 0,
          rotZ: m.rotZ || 0,
          breath: m.breath || 0,
          particles: m.particles || 0,
          edges: m.edges || 0,
          verts: m.verts || 0,
          fps: fpsRef.current,
          packets: pkt,
        });
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const f = (n, w = 2, d = 3) => {
    const s = (n >= 0 ? "+" : "") + n.toFixed(d);
    return s;
  };

  return (
    <div className="mesh-telemetry">
      <div className="mt-block mt-tr">
        <div className="mt-row"><span>X</span><b>{f(Math.sin(t.rotY) * 1.55, 2, 3)}</b></div>
        <div className="mt-row"><span>Y</span><b>{f(Math.cos(t.rotX) * 0.92, 2, 3)}</b></div>
        <div className="mt-row"><span>Z</span><b>{f(Math.sin(t.rotZ * 2) * 0.18 + t.breath * 1.2, 2, 3)}</b></div>
        <div className="mt-row mt-row-acc">
          <span>●</span><b>ACTIVE</b>
        </div>
      </div>

      <div className="mt-block mt-tl">
        <div className="mt-k">SIG</div>
        <div className="mt-mono">PKT&nbsp;{String(t.packets).padStart(6, "0")}</div>
        <div className="mt-mono">FPS&nbsp;{t.fps.toFixed(1)}</div>
        <div className="mt-mono">η&nbsp;&nbsp;{(0.42 + t.breath * 1.5).toFixed(3)}</div>
      </div>

      <div className="mt-block mt-bl">
        <div className="mt-k">MESH</div>
        <div className="mt-mono">V&nbsp;{String(t.verts).padStart(4, "0")}</div>
        <div className="mt-mono">E&nbsp;{String(t.edges).padStart(4, "0")}</div>
        <div className="mt-mono">P&nbsp;{String(t.particles).padStart(4, "0")}</div>
      </div>

      <div className="mt-block mt-br">
        <div className="mt-k">ROT</div>
        <div className="mt-mono">θx&nbsp;{f(t.rotX, 1, 3)}</div>
        <div className="mt-mono">θy&nbsp;{f(t.rotY % (Math.PI * 2), 1, 3)}</div>
        <div className="mt-mono">θz&nbsp;{f(t.rotZ, 1, 3)}</div>
      </div>
    </div>
  );
}

/* ============================================================
   Micrographics overlay — anchored instrument labels with
   leader lines tracking projected brain vertices.
   ============================================================ */
const MICROGRAPHIC_LABELS = [
  { code: "Ø 1.55 r", line: "BASE RADIUS",      side: "right" },
  { code: "320 F",    line: "FACES",            side: "left" },
  { code: "ΔE 0.018", line: "DEFORM ENERGY",    side: "right" },
  { code: "η 0.42",   line: "RECURRENCE",       side: "left" },
  { code: "T 36.7°",  line: "THERMAL",          side: "right" },
];

function MicrographicsOverlay() {
  const wrapRef = React.useRef(null);
  const [anchors, setAnchors] = React.useState([]);
  const [size, setSize] = React.useState({ w: 0, h: 0 });

  React.useEffect(() => {
    let raf;
    const tick = () => {
      const a = (window.__rozumMesh && window.__rozumMesh.anchors) || [];
      if (a.length && wrapRef.current) {
        const r = wrapRef.current.getBoundingClientRect();
        if (r.width !== size.w || r.height !== size.h) {
          setSize({ w: r.width, h: r.height });
        }
        setAnchors(a);
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [size.w, size.h]);

  return (
    <svg ref={wrapRef} className="mesh-micro" preserveAspectRatio="none">
      {anchors.map((a, i) => {
        const meta = MICROGRAPHIC_LABELS[i % MICROGRAPHIC_LABELS.length];
        if (!meta) return null;
        const isRight = meta.side === "right";
        // Label sits at a fixed offset from the anchor toward the edge
        const offset = 70;
        const lx = isRight ? a.x + offset : a.x - offset;
        const ly = a.y - 8;
        // Bend the leader line into an L-shape
        const bx = isRight ? a.x + 16 : a.x - 16;
        const by = a.y;
        return (
          <g key={i}>
            {/* Anchor dot */}
            <circle cx={a.x} cy={a.y} r="2.5" fill="var(--ink)" />
            <circle cx={a.x} cy={a.y} r="5" fill="none" stroke="var(--ink)" strokeOpacity="0.3" />
            {/* Leader line — L bend */}
            <polyline
              points={`${a.x},${a.y} ${bx},${by} ${lx},${ly}`}
              fill="none" stroke="var(--ink)" strokeWidth="0.6" strokeOpacity="0.55"
            />
            {/* Label group */}
            <g transform={`translate(${lx}, ${ly})`}>
              <text
                x={isRight ? 4 : -4}
                y={-4}
                textAnchor={isRight ? "start" : "end"}
                className="micro-code"
              >
                {meta.code}
              </text>
              <text
                x={isRight ? 4 : -4}
                y={8}
                textAnchor={isRight ? "start" : "end"}
                className="micro-line"
              >
                {meta.line}
              </text>
            </g>
          </g>
        );
      })}
    </svg>
  );
}

/* ============================================================
   PAAI core — grainy, atomized rust+metal letters sitting in
   the brain's centre, breathing on the Z axis only.
   ============================================================ */
function PaaiCore() {
  const ref = React.useRef(null);
  React.useEffect(() => {
    let raf;
    const tick = () => {
      const m = window.__rozumMesh && window.__rozumMesh.telemetry;
      if (m && ref.current) {
        // Z translation tied to breath
        const z = m.breath * 120;
        // Tiny grain vibration
        const jx = (Math.random() - 0.5) * 0.6;
        const jy = (Math.random() - 0.5) * 0.6;
        ref.current.style.transform =
          `translate(-50%, -50%) translate3d(${jx}px, ${jy}px, ${z}px)`;
        // Diffused breathing on opacity
        const op = 0.78 + Math.abs(m.breath) * 1.5;
        ref.current.style.opacity = Math.min(1, op);
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <div ref={ref} className="paai-core">
      <svg viewBox="0 0 320 130" preserveAspectRatio="xMidYMid meet">
        <defs>
          <filter id="paai-atomize" x="-20%" y="-20%" width="140%" height="140%">
            <feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" seed="3">
              <animate attributeName="seed" values="3;9;5;11;3" dur="0.6s" repeatCount="indefinite" />
            </feTurbulence>
            <feDisplacementMap in="SourceGraphic" scale="1.6" />
            <feGaussianBlur stdDeviation="0.35" />
          </filter>
          <filter id="paai-grain">
            <feTurbulence type="fractalNoise" baseFrequency="2.4" numOctaves="2" />
            <feColorMatrix values="0 0 0 0 0.18  0 0 0 0 0.08  0 0 0 0 0.03  0 0 0 0.45 0" />
            <feComposite in2="SourceGraphic" operator="in" />
          </filter>
          <linearGradient id="rust-metal" x1="0" x2="1" y1="0" y2="1">
            <stop offset="0" stopColor="#7a3618" />
            <stop offset="0.18" stopColor="#a04a22" />
            <stop offset="0.32" stopColor="#c0c0c0" />
            <stop offset="0.45" stopColor="#b46a3a" />
            <stop offset="0.6" stopColor="#5a2a14" />
            <stop offset="0.74" stopColor="#d8a888" />
            <stop offset="0.88" stopColor="#8a3c1a" />
            <stop offset="1" stopColor="#3a1808" />
          </linearGradient>
          {/* Sporadic metallic shine band */}
          <linearGradient id="metal-shine" x1="0" x2="1" y1="0.2" y2="0.8">
            <stop offset="0" stopColor="#ffffff" stopOpacity="0" />
            <stop offset="0.42" stopColor="#ffffff" stopOpacity="0" />
            <stop offset="0.5" stopColor="#f4eee4" stopOpacity="0.95" />
            <stop offset="0.58" stopColor="#ffffff" stopOpacity="0" />
            <stop offset="1" stopColor="#ffffff" stopOpacity="0" />
          </linearGradient>
        </defs>

        {/* Base rust+metal letters with atomization */}
        <g filter="url(#paai-atomize)">
          <text
            x="160" y="68" textAnchor="middle"
            fontFamily="Archivo, sans-serif"
            fontSize="76" fontWeight="900"
            letterSpacing="-0.04em"
            fill="url(#rust-metal)"
          >
            PAAI
          </text>
        </g>

        {/* Metal shine pass — animated horizontal sweep */}
        <g filter="url(#paai-atomize)" opacity="0.6">
          <text
            x="160" y="68" textAnchor="middle"
            fontFamily="Archivo, sans-serif"
            fontSize="76" fontWeight="900"
            letterSpacing="-0.04em"
            fill="url(#metal-shine)"
          >
            <animate attributeName="x" values="120;200;160;120" dur="6s" repeatCount="indefinite" />
            PAAI
          </text>
        </g>

        {/* Grain overlay */}
        <g filter="url(#paai-grain)" opacity="0.5">
          <text
            x="160" y="68" textAnchor="middle"
            fontFamily="Archivo, sans-serif"
            fontSize="76" fontWeight="900"
            letterSpacing="-0.04em"
            fill="#000"
          >
            PAAI
          </text>
        </g>

        {/* Translation — acronym expansion */}
        <text
          x="160" y="100" textAnchor="middle"
          fontFamily="JetBrains Mono, monospace"
          fontSize="9.5" letterSpacing="3"
          fill="#5a2a14"
          style={{ textTransform: "uppercase" }}
        >
          PRIVATE · AGENTIC · AI
        </text>
      </svg>
    </div>
  );
}

function Hero({ headline, sub }) {
  const [time, setTime] = React.useState("");
  React.useEffect(() => {
    const update = () => {
      const d = new Date();
      const lon = d.toLocaleTimeString("en-GB", {
        timeZone: "Europe/London",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: false,
      });
      setTime(lon);
    };
    update();
    const id = setInterval(update, 1000);
    return () => clearInterval(id);
  }, []);

  return (
    <section className="hero" style={{ borderTop: 0, paddingTop: 32 }}>
      <div className="page">
        <div className="hero-meta-row">
          <div>
            <strong>ROZUMCODE</strong> / AI Systems Advisory, Software Development &amp; Engineering
          </div>
          <div>
            File <strong>R-2026.05</strong> · London Office
          </div>
          <div>
            LON · <strong>{time || "00:00:00"} GMT</strong>
          </div>
          <div>
            Index <strong>01 / 08</strong>
          </div>
        </div>

        <div className="hero-grid">
          <div>
            <div
              style={{
                fontFamily: "var(--ff-mono)",
                fontSize: 11,
                letterSpacing: "0.14em",
                textTransform: "uppercase",
                color: "var(--g-55)",
                display: "flex",
                gap: 24,
                marginBottom: 28,
                flexWrap: "wrap",
              }}
            >
              <span>↳ Doc 001</span>
              <span>Volume I</span>
            </div>

            <h1
              className="hero-title"
              dangerouslySetInnerHTML={{ __html: headline }}
            />

            <p className="hero-sub">{sub}</p>

            <div className="hero-actions">
              <a className="btn" href="mailto:info@rozumcode.com">
                Set a free meeting <span className="arrow"></span>
              </a>
              <a
                href="#services"
                style={{
                  fontFamily: "var(--ff-mono)",
                  fontSize: 11,
                  letterSpacing: "0.12em",
                  textTransform: "uppercase",
                  color: "var(--ink)",
                  borderBottom: "1px solid var(--ink)",
                  paddingBottom: 2,
                }}
              >
                Review capabilities →
              </a>
            </div>
          </div>

          <div className="hero-3d-wrap" style={{ position: "relative" }}>
            <div
              id="hero-3d"
              className="hero-3d feather"
              style={{ width: "100%", aspectRatio: "1 / 1", maxHeight: 620 }}
            ></div>
            <PaaiCore />
            <MicrographicsOverlay />
            <MeshTelemetry />
            <div className="hero-3d-caption">
              <span>FIG. 01 · CORTICAL MESH / 220 NODES</span>
              <span>RENDERED IN REAL-TIME</span>
            </div>
          </div>
        </div>

        <div className="hero-bottom">
          <div className="col">
            <div className="k">Practice</div>
            <div className="v">
              Advisory · Software · AI Engineering · Operations.<br/>Companies, SMEs &amp; regulated&nbsp;enterprise.
            </div>
          </div>
          <div className="col">
            <div className="k">Domains</div>
            <div className="v">
              Software · Embedded · Hardware <br />
              ESP32 · Edge · Cloud
            </div>
          </div>
          <div className="col">
            <div className="k">Frameworks</div>
            <div className="v">
              EU AI Act · ISO 42001 <br />
              NIST AI RMF · GDPR
            </div>
          </div>
          <div className="col">
            <div className="k">Engagement</div>
            <div className="v">
              Advisory · Build <br />
              Production · Run
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero });
