const { useState, useEffect, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "showStrip": true,
  "parallax": true,
  "showField": true
}/*EDITMODE-END*/;

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const fieldRef = useRef(null);

  // Mouse-parallax on the background field
  useEffect(() => {
    if (!tweaks.parallax) {
      document.documentElement.style.setProperty('--mx', '0px');
      document.documentElement.style.setProperty('--my', '0px');
      document.documentElement.style.setProperty('--rx', '0deg');
      document.documentElement.style.setProperty('--ry', '0deg');
      return;
    }
    let raf = 0;
    let tx = 0, ty = 0, cx = 0, cy = 0;
    const onMove = (e) => {
      const w = window.innerWidth, h = window.innerHeight;
      tx = (e.clientX / w - 0.5);
      ty = (e.clientY / h - 0.5);
      if (!raf) raf = requestAnimationFrame(tick);
    };
    const tick = () => {
      cx += (tx - cx) * 0.08;
      cy += (ty - cy) * 0.08;
      document.documentElement.style.setProperty('--mx', `${(cx * 36).toFixed(2)}px`);
      document.documentElement.style.setProperty('--my', `${(cy * 36).toFixed(2)}px`);
      document.documentElement.style.setProperty('--rx', `${(-cy * 2).toFixed(2)}deg`);
      document.documentElement.style.setProperty('--ry', `${(cx * 2).toFixed(2)}deg`);
      if (Math.abs(tx - cx) > 0.001 || Math.abs(ty - cy) > 0.001) {
        raf = requestAnimationFrame(tick);
      } else { raf = 0; }
    };
    window.addEventListener('mousemove', onMove);
    return () => { window.removeEventListener('mousemove', onMove); if (raf) cancelAnimationFrame(raf); };
  }, [tweaks.parallax]);

  return (
    <div className="page">
      {/* Background field — subtle dotted grid + dashed curves + nodes */}
      {tweaks.showField && <BackgroundField />}

      {/* Top: just the wordmark, no menu */}
      <header className="top">
        <div className="brand">
          <Logo size={32} />
          <span className="wordmark">GRAVITHAS</span>
        </div>
      </header>

      {/* Hero */}
      <section className="hero rev">
        <div className="pill">
          <span className="pill-dot" />
          <span>Working on a unified Governability Framework</span>
          <span className="tag">v0.1</span>
        </div>

        <h1 className="headline">
          <span className="l">Predict regime <em>collapse.</em></span>
          <span className="l muted">Monitor governance.</span>
          <span className="l muted">Intervene before failure.</span>
        </h1>

        <p className="lede">
          <strong>Gravithas</strong> builds prediction, monitoring, and intervention
          systems for the hardest problems in AI safety, critical-care medicine,
          financial stability, and infrastructure resilience — built on a unified
          mathematical framework validated across four ontologically distinct domains.
        </p>

        <div className="actions">
          <a className="btn btn-primary" href="mailto:hello@gravithas.org">
            Talk to us <span className="arrow">→</span>
          </a>
          <a className="btn btn-ghost" href="#" target="_blank" rel="noopener">
            Read the science <span className="arrow">→</span>
          </a>
        </div>

        {tweaks.showStrip && (
          <div className="domain-strip" aria-label="Validation domains">
            <div>AI Safety</div>
            <div>Critical Care</div>
            <div>Financial Stability</div>
            <div>Infrastructure</div>
          </div>
        )}
      </section>

      {/* Footer */}
      <footer className="foot">
        <span className="foot-left">
          <span className="foot-dot" />
          Gravithas Lab · 2026
        </span>
        <span className="foot-right">
          Avd. Menéndez Pelayo 41 · Madrid
        </span>
      </footer>

      {/* Tweaks */}
      <TweaksPanel title="Tweaks">
        <TweakSection title="Surface">
          <TweakToggle
            label="Validation strip"
            value={tweaks.showStrip}
            onChange={(v) => setTweak("showStrip", v)}
          />
          <TweakToggle
            label="Background field"
            value={tweaks.showField}
            onChange={(v) => setTweak("showField", v)}
          />
          <TweakToggle
            label="Mouse parallax"
            value={tweaks.parallax}
            onChange={(v) => setTweak("parallax", v)}
          />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

// Background field component — animated dashed curves + dotted grid + nodes.
// Curves use percentage-based paths so they span the visible viewport.
function BackgroundField() {
  // Deterministic pseudo-random nodes
  const W = 1600, H = 900;
  let s = 17;
  const r = () => (s = (s * 9301 + 49297) % 233280) / 233280;
  const nodes = Array.from({ length: 38 }, () => ({
    x: r() * W,
    y: r() * H,
    big: r() < 0.15,
    accent: r() < 0.18,
    delay: (r() * 6).toFixed(2),
    dur: (4 + r() * 4).toFixed(2),
  }));

  // 9 dashed flowing curves spread across the full viewBox so they
  // remain visible at all aspect ratios (preserveAspectRatio="none" stretches).
  const curves = [
    { d: "M -40 80   C 320 30,  640 180, 920 100  S 1380 60,  1700 140", w: 1.0, op: 0.22 },
    { d: "M -40 200  C 280 280, 580 120, 880 220  S 1340 320, 1700 220", w: 1.2, op: 0.30 },
    { d: "M -40 320  C 280 230, 560 380, 880 280  S 1380 200, 1700 320", w: 1.4, op: 0.34 },
    { d: "M -40 440  C 320 520, 600 380, 920 480  S 1380 560, 1700 460", w: 1.2, op: 0.30 },
    { d: "M -40 540  C 240 480, 540 620, 880 520  S 1320 460, 1700 540", w: 1.4, op: 0.36 },
    { d: "M -40 660  C 280 740, 600 600, 900 700  S 1360 780, 1700 680", w: 1.2, op: 0.32 },
    { d: "M -40 760  C 280 700, 580 820, 900 740  S 1360 680, 1700 740", w: 1.0, op: 0.26 },
    { d: "M -40 860  C 360 900, 700 800, 980 880  S 1380 920, 1700 840", w: 1.0, op: 0.22 },
            { d: "M -40 50   C 320 200, 660 700, 980 540  S 1380 300, 1700 600", w: 1.0, op: 0.18, accent: true },
  ];

  return (
    <div className="field" aria-hidden="true">
      <div className="field-grid" />
      <svg className="field-svg" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
        <defs>
          <radialGradient id="vignette" cx="50%" cy="50%" r="65%">
            <stop offset="0%"  stopColor="#000" stopOpacity="0"/>
            <stop offset="60%" stopColor="#000" stopOpacity="0.35"/>
            <stop offset="100%" stopColor="#000" stopOpacity="0.85"/>
          </radialGradient>
        </defs>

        {/* Curves */}
        <g className="field-curves">
          {curves.map((c, i) => (
            <path key={i} d={c.d}
                  fill="none"
                  stroke={c.accent ? "rgba(157, 107, 255, 0.55)" : `rgba(220, 224, 240, ${c.op})`}
                  strokeWidth={c.w}
                  strokeDasharray="3 9"
                  strokeLinecap="round"
                  vectorEffect="non-scaling-stroke"
                  className={`field-curve fc-${i}`}
                  style={{ animationDelay: `${i * 0.8}s` }} />
          ))}
        </g>

        {/* Nodes (preserve aspect locally with non-scaling stroke) */}
        <g className="field-nodes">
          {nodes.map((n, i) => (
            <g key={i} transform={`translate(${n.x},${n.y})`}>
              <circle r={n.big ? 4 : 2.2}
                      fill={n.accent ? "#9d6bff" : "#cdd2e8"}
                      opacity={n.accent ? 0.65 : 0.36}
                      style={{ animationDelay: `${n.delay}s`, animationDuration: `${n.dur}s` }}
                      className="field-node" />
              {n.big && (
                <circle r="9" fill="none"
                        stroke={n.accent ? "#9d6bff" : "#cdd2e8"}
                        strokeOpacity="0.20"
                        strokeWidth="1"
                        vectorEffect="non-scaling-stroke" />
              )}
            </g>
          ))}
        </g>

        {/* Vignette to focus center */}
        <rect width={W} height={H} fill="url(#vignette)" />
      </svg>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
