/* global React */
/* ====================================================================
   Graphics & decorative components — aurora, topo lines, stars, HUD,
   capability icons, and a topographic field-map section.
   The goal: signal forest + arctic, restrained, animated.
   ==================================================================== */

const { useMemo, useState, useEffect, useRef } = React;

/* ---- 1. Aurora glows (3 soft, drifting radial blobs) ---- */
function Aurora() {
  return (
    <div className="aurora" aria-hidden>
      <div className="aurora-glow a" />
      <div className="aurora-glow b" />
      <div className="aurora-glow c" />
    </div>
  );
}

/* ---- 2. Hero topo — ridgelines via stacked sine waves ---- */
function HeroTopo() {
  const { W, H, lines } = useMemo(() => {
    const W = 1600, H = 900;
    const lines = [];
    for (let i = 0; i < 22; i++) {
      const baseY = 80 + (i / 21) * (H - 80);
      let d = `M 0 ${baseY}`;
      for (let x = 0; x <= W; x += 18) {
        const off =
          Math.sin(x / 180 + i * 0.61) * (30 - i * 0.7) +
          Math.sin(x / 72 + i * 1.4) * 6 +
          Math.sin(x / 360 - i * 0.27) * 18;
        d += ` L ${x} ${baseY + off}`;
      }
      lines.push(d);
    }
    return { W, H, lines };
  }, []);
  return (
    <svg
      className="hero-topo"
      viewBox={`0 0 ${W} ${H}`}
      preserveAspectRatio="xMidYMid slice"
      aria-hidden
    >
      {lines.map((d, i) => (
        <path key={i} d={d} style={{ animationDelay: `${i * 0.08}s` }} />
      ))}
    </svg>
  );
}

/* ---- 3. Stars / particles ---- */
function Stars({ count = 90 }) {
  const stars = useMemo(() => {
    return Array.from({ length: count }).map((_, i) => {
      const x = (i * 137.508) % 100;
      const y = (i * 53.71 + (i % 5) * 7.3) % 100;
      const size = (i % 4) + 1;
      const delay = (i % 9) * 0.4;
      const dur = 3 + (i % 5);
      return { x, y, size, delay, dur };
    });
  }, [count]);
  return (
    <div className="stars" aria-hidden>
      {stars.map((s, i) => (
        <span
          key={i}
          className="star"
          style={{
            left: s.x + "%",
            top: s.y + "%",
            width: s.size + "px",
            height: s.size + "px",
            animationDelay: s.delay + "s",
            animationDuration: s.dur + "s",
          }}
        />
      ))}
    </div>
  );
}

/* ---- 4. Hero HUD — instrument readout, top right ---- */
function HeroHUD() {
  const [time, setTime] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => setTime(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  const utc = time.toISOString().slice(11, 19);
  return (
    <div className="hero-hud" aria-hidden>
      <div className="hud-row"><span className="k">SYS</span><span className="v">CKR-01</span></div>
      <div className="hud-row"><span className="k">LAT</span><span className="v">64.84° N</span></div>
      <div className="hud-row"><span className="k">LON</span><span className="v">147.72° W</span></div>
      <div className="hud-row"><span className="k">UTC</span><span className="v">{utc}</span></div>
      <div className="hud-row">
        <span className="k">STATUS</span>
        <span className="v"><span className="hud-dot" /> NOMINAL</span>
      </div>
    </div>
  );
}

/* ---- 5. Capability icons ---- */
function SaasIcon() {
  return (
    <svg className="cap-icon" viewBox="0 0 64 64" aria-hidden>
      <line x1="32" y1="2" x2="32" y2="62" className="dim" />
      <line x1="2" y1="32" x2="62" y2="32" className="dim" />
      <rect x="6" y="6" width="20" height="20" />
      <rect x="38" y="6" width="20" height="20" />
      <rect x="6" y="38" width="20" height="20" />
      <rect x="38" y="38" width="20" height="20" className="filled" />
    </svg>
  );
}
function SecurityIcon() {
  return (
    <svg className="cap-icon" viewBox="0 0 64 64" aria-hidden>
      <circle cx="32" cy="32" r="4" className="filled" />
      <circle cx="32" cy="32" r="12" />
      <circle cx="32" cy="32" r="22" className="dim" />
      <circle cx="32" cy="32" r="30" className="dim" />
      <line x1="32" y1="2" x2="32" y2="14" />
      <line x1="32" y1="50" x2="32" y2="62" />
      <line x1="2" y1="32" x2="14" y2="32" />
      <line x1="50" y1="32" x2="62" y2="32" />
      <circle cx="51" cy="13" r="2" className="filled" />
    </svg>
  );
}
function AgenticIcon() {
  return (
    <svg className="cap-icon" viewBox="0 0 64 64" aria-hidden>
      <line x1="10" y1="14" x2="42" y2="30" />
      <line x1="10" y1="14" x2="22" y2="52" />
      <line x1="42" y1="30" x2="22" y2="52" />
      <line x1="42" y1="30" x2="56" y2="14" />
      <line x1="42" y1="30" x2="52" y2="54" />
      <line x1="22" y1="52" x2="52" y2="54" />
      <circle cx="10" cy="14" r="3" className="filled" />
      <circle cx="42" cy="30" r="3" className="filled" />
      <circle cx="22" cy="52" r="3" className="filled" />
      <circle cx="56" cy="14" r="3" />
      <circle cx="52" cy="54" r="3" />
    </svg>
  );
}
const Icons = { saas: SaasIcon, security: SecurityIcon, agentic: AgenticIcon };

/* ---- Crooker brand mark — geometric icosahedron projection ---- */
function BrandMark() {
  return (
    <svg className="bm" viewBox="0 0 32 32" aria-hidden>
      <circle cx="16" cy="16" r="15.2" className="bm-bg" />
      {/* Hexagonal silhouette */}
      <polygon className="bm-stroke" points="16,4 26.4,10 26.4,22 16,28 5.6,22 5.6,10" />
      {/* Two overlapping triangles forming a hexagram */}
      <polygon className="bm-stroke" points="16,4 26.4,22 5.6,22" />
      <polygon className="bm-stroke bm-fill" points="26.4,10 16,28 5.6,10" />
      {/* Center vertex node */}
      <circle cx="16" cy="16" r="1.6" className="bm-dot" />
      {/* Spokes from center to outer vertices */}
      <line x1="16" y1="16" x2="16" y2="4" className="bm-spoke" />
      <line x1="16" y1="16" x2="26.4" y2="10" className="bm-spoke" />
      <line x1="16" y1="16" x2="26.4" y2="22" className="bm-spoke" />
      <line x1="16" y1="16" x2="16" y2="28" className="bm-spoke" />
      <line x1="16" y1="16" x2="5.6" y2="22" className="bm-spoke" />
      <line x1="16" y1="16" x2="5.6" y2="10" className="bm-spoke" />
    </svg>
  );
}

/* ---- 6. Horizon — layered mountain landscape strip ---- */
function Horizon() {
  const { W, H, ridges, pines, stars } = useMemo(() => {
    const W = 1920, H = 460;
    const ridge = (seed, baseY, amp, freq) => {
      const pts = [`0 ${H}`];
      for (let x = 0; x <= W; x += 14) {
        const y =
          baseY +
          Math.sin(x / freq + seed) * amp +
          Math.sin(x / (freq * 0.42) + seed * 1.7) * amp * 0.28 +
          Math.cos(x / (freq * 2.1) + seed * 0.5) * amp * 0.45;
        pts.push(`${x.toFixed(1)} ${y.toFixed(1)}`);
      }
      pts.push(`${W} ${H}`);
      return pts.join(" ");
    };
    const ridges = [
      { d: ridge(1.1, 150, 38, 220), cls: "ridge ridge-1" },
      { d: ridge(2.6, 210, 50, 180), cls: "ridge ridge-2" },
      { d: ridge(3.9, 280, 58, 140), cls: "ridge ridge-3" },
      { d: ridge(5.2, 350, 64, 100), cls: "ridge ridge-4" },
    ];
    const pines = [];
    for (let i = 0; i < 42; i++) {
      const x = (i / 41) * W + Math.sin(i * 17.3) * 16;
      const h = 28 + Math.abs(Math.sin(i * 5.7)) * 24;
      const w = 5 + Math.abs(Math.cos(i * 3.1)) * 2;
      pines.push({ x, h, w });
    }
    const stars = [];
    for (let i = 0; i < 36; i++) {
      const x = (i * 137.5) % W;
      const y = 10 + ((i * 53.1) % 110);
      const r = ((i % 3) + 1) * 0.6;
      stars.push({ x, y, r });
    }
    return { W, H, ridges, pines, stars };
  }, []);

  return (
    <div className="horizon" aria-hidden>
      <svg
        className="horizon-svg"
        viewBox={`0 0 ${W} ${H}`}
        preserveAspectRatio="xMidYMax slice"
      >
        {stars.map((s, i) => (
          <circle key={"s" + i} cx={s.x} cy={s.y} r={s.r} className="h-star" />
        ))}
        <circle cx={W * 0.78} cy={88} r="46" className="moon-glow" />
        <circle cx={W * 0.78} cy={88} r="28" className="moon" />
        <path
          d={`M 0 110 Q ${W * 0.25} 56 ${W * 0.5} 130 T ${W} 88 L ${W} 172 Q ${W * 0.7} 200 ${W * 0.4} 180 T 0 200 Z`}
          className="aurora-band-svg"
        />
        {ridges.map((r, i) => (
          <polygon key={i} points={r.d} className={r.cls} />
        ))}
        {pines.map((p, i) => (
          <polygon
            key={"p" + i}
            className="pine"
            points={`${p.x - p.w} ${H - 38} ${p.x} ${H - 38 - p.h} ${p.x + p.w} ${H - 38}`}
          />
        ))}
        <rect x="0" y={H - 38} width={W} height="38" className="ground" />
      </svg>
      <div className="horizon-corners" aria-hidden>
        <span className="hc bl">64.84° N · BOREAL TIMBERLINE</span>
        <span className="hc br">ELEV. 240 M · MAGNETIC NORTH ↑</span>
      </div>
    </div>
  );
}

/* ---- 7. Terrain — topographic field map section ---- */
function Terrain() {
  const { W, H, rings } = useMemo(() => {
    const W = 1600, H = 700;
    const cx = 800, cy = 360;
    const rings = [];
    for (let i = 0; i < 14; i++) {
      const r0 = 60 + i * 38;
      let d = "";
      for (let a = 0; a <= 360; a += 4) {
        const rad = (a * Math.PI) / 180;
        const wobble =
          Math.sin(a / 22 + i * 0.5) * (14 + i * 1.2) +
          Math.sin(a / 7 + i * 1.1) * 5 +
          Math.cos(a / 40 - i * 0.4) * 8;
        const r = r0 + wobble;
        const x = cx + r * Math.cos(rad);
        const y = cy + r * Math.sin(rad) * 0.62;
        d += (a === 0 ? "M " : "L ") + x.toFixed(1) + " " + y.toFixed(1) + " ";
      }
      d += "Z";
      rings.push(d);
    }
    return { W, H, rings };
  }, []);
  // Small annotated stations
  const stations = [
    { x: 800, y: 360, label: "STATION ALPHA", sub: "primary engagement" },
    { x: 560, y: 220, label: "STATION BRAVO", sub: "diagnostic" },
    { x: 1080, y: 480, label: "STATION CHARLIE", sub: "hand-off" },
    { x: 940, y: 200, label: "OBS-04", sub: "monitoring" },
  ];

  return (
    <section className="terrain">
      <div className="terrain-overlay shell">
        <div className="terrain-head">
          <div>
            <div className="eyebrow">[~~] Field map</div>
            <h2 className="terrain-title">Technology, plotted as <span className="ser">terrain</span>.</h2>
          </div>
          <p className="terrain-sub">
            Every engagement is mapped, instrumented, and gridded. We treat the
            unknowns of a system the way a surveyor treats a mountain. Measured, named, and ready to walk.
          </p>
        </div>
      </div>
      <div className="terrain-canvas">
        <svg
          className="terrain-svg"
          viewBox={`0 0 ${W} ${H}`}
          preserveAspectRatio="xMidYMid slice"
          aria-hidden
        >
          {/* grid */}
          <g className="terrain-grid">
            {Array.from({ length: 24 }).map((_, i) => (
              <line key={"v" + i} x1={(i * W) / 24} y1="0" x2={(i * W) / 24} y2={H} />
            ))}
            {Array.from({ length: 12 }).map((_, i) => (
              <line key={"h" + i} x1="0" y1={(i * H) / 12} x2={W} y2={(i * H) / 12} />
            ))}
          </g>
          {/* contour rings */}
          {rings.map((d, i) => (
            <path key={i} d={d} className={"terrain-ring r-" + (i % 4)} />
          ))}
          {/* stations */}
          {stations.map((s, i) => (
            <g key={i} className="terrain-station" transform={`translate(${s.x} ${s.y})`}>
              <circle r="3.5" className="dot" />
              <line x1="0" y1="0" x2="80" y2="-50" />
              <text x="88" y="-50">{s.label}</text>
              <text x="88" y="-36" className="sub">{s.sub}</text>
            </g>
          ))}
        </svg>
        <div className="terrain-corners" aria-hidden>
          <span className="tc tl">64.84° N · 147.72° W</span>
          <span className="tc tr">EL. 1240 M</span>
          <span className="tc bl">SHEET 04 / 12</span>
          <span className="tc br">CKR · FIELD</span>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  Aurora, HeroTopo, Stars, HeroHUD,
  SaasIcon, SecurityIcon, AgenticIcon, Icons,
  BrandMark,
  Terrain, Horizon,
});
