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

// ============================================================
// Neural constellation — animated, echoes the logo
// ============================================================
function NeuralField({ accent, highlight, muted }) {
  const canvasRef = useRef(null);
  const rafRef = useRef(0);
  const pointsRef = useRef([]);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const dpr = window.devicePixelRatio || 1;

    function resize() {
      const rect = canvas.getBoundingClientRect();
      canvas.width = rect.width * dpr;
      canvas.height = rect.height * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    }
    resize();
    const ro = new ResizeObserver(resize);
    ro.observe(canvas);

    // Build a constellation reminiscent of the logo: outer ring of "blue" nodes,
    // inner cluster of "highlight" nodes with dense interconnects.
    const W = () => canvas.getBoundingClientRect().width;
    const H = () => canvas.getBoundingClientRect().height;

    function buildPoints() {
      const pts = [];
      const cx = W() / 2;
      const cy = H() / 2;
      const R = Math.min(W(), H()) * 0.42;

      // Outer ring (blue)
      const outer = 38;
      for (let i = 0; i < outer; i++) {
        const a = (i / outer) * Math.PI * 2;
        const rr = R * (0.78 + Math.random() * 0.22);
        pts.push({
          x: cx + Math.cos(a) * rr,
          y: cy + Math.sin(a) * rr,
          base: { x: cx + Math.cos(a) * rr, y: cy + Math.sin(a) * rr },
          phase: Math.random() * Math.PI * 2,
          r: 2.2 + Math.random() * 1.2,
          group: 'outer',
        });
      }
      // Inner ring (blue, intermediate)
      const mid = 22;
      for (let i = 0; i < mid; i++) {
        const a = (i / mid) * Math.PI * 2 + 0.1;
        const rr = R * (0.45 + Math.random() * 0.12);
        pts.push({
          x: cx + Math.cos(a) * rr,
          y: cy + Math.sin(a) * rr,
          base: { x: cx + Math.cos(a) * rr, y: cy + Math.sin(a) * rr },
          phase: Math.random() * Math.PI * 2,
          r: 2.0 + Math.random() * 1.0,
          group: 'mid',
        });
      }
      // Inner cluster (highlight / orange)
      const inner = 14;
      for (let i = 0; i < inner; i++) {
        const a = (i / inner) * Math.PI * 2 + 0.3;
        const rr = R * (0.12 + Math.random() * 0.14);
        pts.push({
          x: cx + Math.cos(a) * rr,
          y: cy + Math.sin(a) * rr,
          base: { x: cx + Math.cos(a) * rr, y: cy + Math.sin(a) * rr },
          phase: Math.random() * Math.PI * 2,
          r: 2.8 + Math.random() * 1.2,
          group: 'inner',
        });
      }
      return pts;
    }
    pointsRef.current = buildPoints();

    function draw(t) {
      const w = W();
      const h = H();
      ctx.clearRect(0, 0, w, h);
      const pts = pointsRef.current;

      // Gentle orbital motion
      for (const p of pts) {
        const osc = Math.sin(t * 0.0005 + p.phase) * 3;
        const rot = t * 0.00003 * (p.group === 'inner' ? -1 : 1);
        const dx = p.base.x - w / 2;
        const dy = p.base.y - h / 2;
        const cos = Math.cos(rot), sin = Math.sin(rot);
        p.x = w / 2 + dx * cos - dy * sin + osc * 0.3;
        p.y = h / 2 + dx * sin + dy * cos + osc * 0.3;
      }

      // Edges
      ctx.lineWidth = 0.6;
      for (let i = 0; i < pts.length; i++) {
        for (let j = i + 1; j < pts.length; j++) {
          const a = pts[i], b = pts[j];
          const dx = a.x - b.x, dy = a.y - b.y;
          const d2 = dx * dx + dy * dy;
          const limit = a.group === 'inner' && b.group === 'inner' ? 200 : 130;
          if (d2 > limit * limit) continue;
          const alpha = 1 - Math.sqrt(d2) / limit;
          let color;
          if (a.group === 'inner' && b.group === 'inner') color = highlight;
          else if (a.group === 'inner' || b.group === 'inner') color = highlight;
          else color = muted;
          ctx.globalAlpha = alpha * (a.group === 'inner' && b.group === 'inner' ? 0.55 : 0.22);
          ctx.strokeStyle = color;
          ctx.beginPath();
          ctx.moveTo(a.x, a.y);
          ctx.lineTo(b.x, b.y);
          ctx.stroke();
        }
      }

      // Nodes
      ctx.globalAlpha = 1;
      for (const p of pts) {
        const pulse = 0.7 + 0.3 * Math.sin(t * 0.002 + p.phase);
        if (p.group === 'inner') {
          ctx.fillStyle = highlight;
          ctx.shadowColor = highlight;
          ctx.shadowBlur = 8 * pulse;
        } else {
          ctx.fillStyle = accent;
          ctx.shadowBlur = 0;
        }
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.r * (p.group === 'inner' ? pulse : 1), 0, Math.PI * 2);
        ctx.fill();
      }
      ctx.shadowBlur = 0;

      rafRef.current = requestAnimationFrame(draw);
    }
    rafRef.current = requestAnimationFrame(draw);
    return () => {
      cancelAnimationFrame(rafRef.current);
      ro.disconnect();
    };
  }, [accent, highlight, muted]);

  return <canvas ref={canvasRef} style={{ width: '100%', height: '100%', display: 'block' }} />;
}

// ============================================================
// Live ticker — uses real time + smooth monotonic changes
// ============================================================
function useTicker(intervalMs = 1000) {
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), intervalMs);
    return () => clearInterval(id);
  }, [intervalMs]);
  return tick;
}

function RelativeTime({ baseSeconds = 247 }) {
  const [seconds, setSeconds] = useState(baseSeconds);
  useEffect(() => {
    const id = setInterval(() => setSeconds(s => s + 1), 1000);
    return () => clearInterval(id);
  }, []);
  if (seconds < 60) return <>{seconds}s ago</>;
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  return <>{m}m {s}s ago</>;
}

// ============================================================
// Hero
// ============================================================
function Hero({ variant, onRequestAccess }) {
  const tick = useTicker(1200);
  const nodes = 847 + (tick % 7);
  const rels = 3204 + (tick % 13);

  // Cycle live events
  const events = useMemo(() => [
    { tag: 'SIGNAL', text: 'Single point of expertise detected across four critical workstreams', risk: 'high' },
    { tag: 'MATCH', text: 'New engagement matched to four qualified people in seconds', risk: 'match' },
    { tag: 'TIMING', text: 'Deadline in 18 days — historical pace suggests 22', risk: 'risk' },
    { tag: 'ANSWER', text: '"Who has led work like this before?" — answered, with sources', risk: 'ok' },
    { tag: 'UPDATE', text: 'Twelve new capabilities verified and added to your map', risk: 'ok' },
  ], []);
  const [evtIdx, setEvtIdx] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setEvtIdx(i => (i + 1) % events.length), 3200);
    return () => clearInterval(id);
  }, [events.length]);

  const palette = {
    accent: 'var(--accent)',
    highlight: 'var(--highlight)',
    muted: 'var(--edge-muted)',
  };

  return (
    <section className="hero" data-variant={variant}>
      <div className="hero-field">
        <NeuralField accent="rgba(70,110,160,0.6)" highlight="rgba(220,100,60,0.9)" muted="rgba(90,130,180,0.35)" />
      </div>

      <div className="hero-grid">
        {/* LEFT: editorial headline */}
        <div className="hero-copy">
          <div className="eyebrow">
            <span className="eyebrow-dash" />
            <span>Agent Operating System · Est. 2026</span>
          </div>

          <h1 className="headline">
            <span>Your organization</span>
            <span className="headline-italic">already knows</span>
            <span>the answer.</span>
          </h1>

          <p className="deck">
            Eloreum is an enterprise AI agent OS that turns <em>what your people know</em> into a graph your whole org can query — before anyone thinks to ask.
          </p>

          <div className="cta-row">
            <button className="btn-primary" onClick={onRequestAccess}>
              <span>Request Early Access</span>
              <span className="btn-arrow">→</span>
            </button>
            <div className="limited">
              <span className="pulse-dot" />
              <span>Limited beta · 14 design-partner slots</span>
            </div>
          </div>

          <div className="marquee-specs">
            <span>Incredibly scalable</span>
            <span>·</span>
            <span>Instantly available</span>
            <span>·</span>
            <span>Robust security</span>
            <span>·</span>
            <span>Rapid curation of your private corpora</span>
            <span>·</span>
            <span>Private to your tenant enclave</span>
          </div>
        </div>

        {/* RIGHT: live system panel */}
        <div className="hero-panel" role="complementary" aria-label="Live workforce intelligence">
          <div className="panel-chrome">
            <div className="panel-chrome-left">
              <span className="panel-bullets">
                <i /><i /><i />
              </span>
              <span className="panel-title">live intelligence</span>
            </div>
            <div className="panel-chrome-right">
              <span className="live-dot" />
              <span>ACTIVE</span>
            </div>
          </div>

          <div className="panel-body">
            {/* Risk register */}
            <div className="risk-table">
              <div className="risk-row risk-head">
                <span>CAPABILITY · DEPTH</span>
                <span>COVERAGE</span>
              </div>
              <RiskRow label="Core Domain Expertise" status="1 person" risk="critical" />
              <RiskRow label="Technical Leadership" status="2 people" risk="high" />
              <RiskRow label="Client Relationships" status="Moderate" risk="moderate" />
              <RiskRow label="Operational Knowledge" status="Covered" risk="ok" />
            </div>

            <div className="panel-meta">
              <span>↻ refreshed <RelativeTime /></span>
              <span>·</span>
              <span>{nodes.toLocaleString()} people mapped</span>
              <span>·</span>
              <span>{rels.toLocaleString()} connections</span>
            </div>

            {/* Event stream */}
            <div className="event-wrap">
              {events.map((e, i) => (
                <div
                  key={e.tag}
                  className="event-card"
                  data-active={i === evtIdx}
                  style={{ opacity: i === evtIdx ? 1 : 0.35 }}
                >
                  <div className="event-head">
                    <span className="event-tag">{e.tag}</span>
                    <span className="event-time">06:{14 + i}</span>
                  </div>
                  <div className="event-body">{e.text}</div>
                  <div className={`event-badge badge-${e.risk}`}>
                    {e.risk === 'high' ? 'Single Point' : e.risk === 'match' ? '91% match' : e.risk === 'risk' ? 'At Risk' : e.risk === 'critical' ? 'Critical' : 'Sourced'}
                  </div>
                </div>
              ))}
            </div>

            {/* Trust & reasoning */}
            <div className="trace">
              <div className="trace-head">
                <span>working on your behalf</span>
                <span className="trace-right">trust level <b>TRUSTED</b> · ★★★★☆ 4.6</span>
              </div>
              <div className="trace-lines">
                <TraceLine step="SENSE" text="three signals in the last hour worth your attention" tick={tick} />
                <TraceLine step="UNDERSTAND" text="context matched · risk weighed · tone calibrated" tick={tick} delay={0.25} />
                <TraceLine step="DECIDE" text="surfacing capability gap before it becomes a problem" tick={tick} delay={0.5} />
                <TraceLine step="DELIVER" text="drafted · independently verified · ready for review" tick={tick} delay={0.75} />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="hero-ribbon">
        <span>EST · 2026</span>
        <span className="ribbon-sep" />
        <span>SOC 2 · seeking</span>
        <span className="ribbon-sep" />
        <span>Encrypted at rest · encrypted in transit</span>
        <span className="ribbon-sep" />
        <span>Private deployment available</span>
      </div>
    </section>
  );
}

function RiskRow({ label, status, risk }) {
  return (
    <div className="risk-row">
      <span className="risk-label">{label}</span>
      <span className={`risk-chip risk-${risk}`}>{status}</span>
    </div>
  );
}

function TraceLine({ step, text, tick, delay = 0 }) {
  // fade in with staggered delay each cycle
  const cycle = tick % 4;
  return (
    <div className="trace-line">
      <span className="trace-step">{step}</span>
      <span className="trace-text">{text}</span>
    </div>
  );
}

window.Hero = Hero;
