// Three Hero visual variants
// 1) "code-flow"   — streaming code rivers in a perspective grid
// 2) "neural"      — clustered neural nodes with traveling pulses
// 3) "bento"       — live operations dashboard with mini widgets

const { useEffect, useRef, useState } = React;

// ------------------------- VARIANT 1: CODE FLOW -------------------------
function HeroCodeFlow({ accent }) {
  const canvasRef = useRef(null);
  const motionRef = useRef(parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--motion')) || 1);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    let w = 0, h = 0;
    function resize() {
      const r = canvas.getBoundingClientRect();
      w = r.width; h = r.height;
      canvas.width = w * dpr; canvas.height = h * dpr;
      ctx.setTransform(dpr,0,0,dpr,0,0);
    }
    resize();
    const ro = new ResizeObserver(resize);
    ro.observe(canvas);

    const cols = 36;
    const glyphs = "01<>{}[]/$;:=*+#░▒▓▮▯■▢◆◇◍◎─│┌┐└┘├┤┬┴┼".split("");
    const drops = Array.from({length: cols}, () => ({
      y: Math.random() * -200,
      v: 0.4 + Math.random() * 1.2,
      hot: Math.random() < 0.12,
    }));

    let raf = 0;
    function tick() {
      const motion = motionRef.current;
      if (motion <= 0.01) { raf = requestAnimationFrame(tick); return; }
      ctx.fillStyle = 'rgba(7,7,10,0.18)';
      if (document.documentElement.dataset.theme === 'light') ctx.fillStyle = 'rgba(250,250,247,0.22)';
      ctx.fillRect(0,0,w,h);

      const cw = w / cols;
      ctx.font = `${Math.max(12, Math.floor(cw * 0.85))}px 'Geist Mono', monospace`;

      drops.forEach((d, i) => {
        const g = glyphs[(Math.random() * glyphs.length) | 0];
        const x = i * cw + cw * 0.15;
        if (d.hot) {
          ctx.fillStyle = accent;
          ctx.shadowColor = accent;
          ctx.shadowBlur = 12;
        } else {
          const light = document.documentElement.dataset.theme === 'light';
          ctx.fillStyle = light ? 'rgba(10,10,15,0.42)' : 'rgba(220,220,235,0.55)';
          ctx.shadowBlur = 0;
        }
        ctx.fillText(g, x, d.y);
        ctx.shadowBlur = 0;

        d.y += d.v * (3 + Math.random() * 2) * motion;
        if (d.y > h + 20) { d.y = -20; d.v = 0.4 + Math.random() * 1.2; d.hot = Math.random() < 0.12; }
      });
      raf = requestAnimationFrame(tick);
    }
    raf = requestAnimationFrame(tick);

    const mo = new MutationObserver(() => {
      motionRef.current = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--motion')) || 1;
    });
    mo.observe(document.documentElement, { attributes: true, attributeFilter: ['style', 'data-theme'] });

    return () => { cancelAnimationFrame(raf); ro.disconnect(); mo.disconnect(); };
  }, [accent]);

  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
      <canvas ref={canvasRef} style={{ width: '100%', height: '100%', display: 'block', opacity: 0.85 }} />
      <div style={{
        position: 'absolute', inset: 0,
        background: `radial-gradient(ellipse 70% 50% at 50% 40%, transparent 0%, var(--bg) 75%)`,
        pointerEvents: 'none'
      }} />
    </div>
  );
}

// ------------------------- VARIANT 2: NEURAL -------------------------
function HeroNeural({ accent }) {
  const ref = useRef(null);
  useEffect(() => {
    const svg = ref.current;
    if (!svg) return;
    const W = 1200, H = 700;
    const layers = [2, 5, 7, 5, 3];
    const xStep = W / (layers.length + 1);
    const nodes = [];
    layers.forEach((count, li) => {
      const x = xStep * (li + 1);
      const yStep = H / (count + 1);
      for (let i = 0; i < count; i++) {
        nodes.push({ id: `${li}-${i}`, layer: li, x, y: yStep * (i + 1) });
      }
    });
    const edges = [];
    for (let li = 0; li < layers.length - 1; li++) {
      const a = nodes.filter(n => n.layer === li);
      const b = nodes.filter(n => n.layer === li + 1);
      a.forEach(na => b.forEach(nb => edges.push({ a: na, b: nb })));
    }

    svg.innerHTML = "";
    const NS = "http://www.w3.org/2000/svg";

    // Edges
    edges.forEach((e, i) => {
      const line = document.createElementNS(NS, 'line');
      line.setAttribute('x1', e.a.x); line.setAttribute('y1', e.a.y);
      line.setAttribute('x2', e.b.x); line.setAttribute('y2', e.b.y);
      line.setAttribute('stroke', 'currentColor');
      line.setAttribute('stroke-width', '0.6');
      line.setAttribute('opacity', '0.22');
      svg.appendChild(line);
    });

    // Pulse paths
    const pulseEdges = edges.filter((_, i) => i % 9 === 0);
    pulseEdges.forEach((e, i) => {
      const c = document.createElementNS(NS, 'circle');
      c.setAttribute('r', '2.2');
      c.setAttribute('fill', accent);
      c.setAttribute('filter', 'url(#glow)');
      const anim = document.createElementNS(NS, 'animateMotion');
      anim.setAttribute('dur', `${2.5 + (i % 5) * 0.7}s`);
      anim.setAttribute('repeatCount', 'indefinite');
      anim.setAttribute('begin', `${(i % 9) * 0.25}s`);
      anim.setAttribute('path', `M ${e.a.x},${e.a.y} L ${e.b.x},${e.b.y}`);
      c.appendChild(anim);
      svg.appendChild(c);
    });

    // Nodes
    nodes.forEach((n, i) => {
      const c = document.createElementNS(NS, 'circle');
      c.setAttribute('cx', n.x); c.setAttribute('cy', n.y);
      c.setAttribute('r', n.layer === 0 || n.layer === layers.length - 1 ? 4.5 : 3);
      const isAccent = i % 7 === 0;
      c.setAttribute('fill', isAccent ? accent : 'currentColor');
      c.setAttribute('opacity', isAccent ? '1' : '0.6');
      if (isAccent) c.setAttribute('filter', 'url(#glow)');
      svg.appendChild(c);
    });

    // Defs (glow)
    const defs = document.createElementNS(NS, 'defs');
    defs.innerHTML = `<filter id="glow"><feGaussianBlur stdDeviation="2.5" /></filter>`;
    svg.appendChild(defs);
  }, [accent]);

  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
      <svg ref={ref} viewBox="0 0 1200 700" preserveAspectRatio="xMidYMid slice"
        style={{ width: '100%', height: '100%', color: 'var(--fg-2)', opacity: 0.9 }} />
      <div style={{
        position: 'absolute', inset: 0,
        background: `radial-gradient(ellipse 70% 60% at 60% 50%, transparent 0%, var(--bg) 80%)`,
        pointerEvents: 'none'
      }} />
    </div>
  );
}

// ------------------------- VARIANT 3: BENTO DASHBOARD -------------------------
function MiniSparkline({ color, seed = 1 }) {
  const pts = React.useMemo(() => {
    const n = 24;
    let v = 50;
    const out = [];
    for (let i = 0; i < n; i++) {
      v += (Math.sin(i * 0.7 + seed) + (Math.random() - 0.5)) * 6;
      v = Math.max(10, Math.min(90, v));
      out.push([i * (100 / (n - 1)), 100 - v]);
    }
    return out;
  }, [seed]);
  const d = "M" + pts.map(p => p.join(",")).join(" L ");
  return (
    <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ width: '100%', height: '100%' }}>
      <path d={d} fill="none" stroke={color} strokeWidth="1.5" />
      <path d={d + " L 100 100 L 0 100 Z"} fill={color} opacity="0.12" />
    </svg>
  );
}

function LiveBar({ accent, label, value, target }) {
  const [v, setV] = useState(value);
  useEffect(() => {
    const motion = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--motion')) || 1;
    if (motion < 0.05) { setV(target); return; }
    let id = setInterval(() => {
      setV(prev => {
        const step = (target - prev) * 0.08 + (Math.random() - 0.5) * 1.5;
        return Math.max(0, Math.min(100, prev + step));
      });
    }, 80);
    return () => clearInterval(id);
  }, [target]);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--fg-2)' }}>
      <span style={{ width: 78, color: 'var(--fg-3)' }}>{label}</span>
      <div style={{ flex: 1, height: 6, background: 'var(--line)', borderRadius: 3, overflow: 'hidden' }}>
        <div style={{ width: `${v}%`, height: '100%', background: accent, transition: 'width .25s' }} />
      </div>
      <span style={{ width: 36, textAlign: 'right', color: 'var(--fg)' }}>{v.toFixed(0)}</span>
    </div>
  );
}

function HeroBento({ accent }) {
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const motion = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--motion')) || 1;
    if (motion < 0.05) return;
    const id = setInterval(() => setTick(t => t + 1), 2200);
    return () => clearInterval(id);
  }, []);

  const card = {
    background: 'var(--surface)',
    border: '1px solid var(--line)',
    borderRadius: 14,
    padding: 14,
    display: 'flex',
    flexDirection: 'column',
    gap: 8,
    minHeight: 0,
  };

  return (
    <div style={{ position: 'absolute', inset: 0, padding: '6vh 4vw', display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gridTemplateRows: 'repeat(4, 1fr)', gap: 14, opacity: 0.72 }}>
      {/* Hero label */}
      <div style={{ ...card, gridColumn: '1 / span 2', gridRow: '1 / span 1' }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.18em' }}>LIVE</div>
        <div style={{ fontSize: 20, fontWeight: 600, color: 'var(--fg)' }}>uptime <span style={{ color: accent }}>99.98%</span></div>
        <div style={{ flex: 1, minHeight: 24 }}>
          <MiniSparkline color={accent} seed={tick} />
        </div>
      </div>
      {/* Big screen */}
      <div style={{ ...card, gridColumn: '3 / span 2', gridRow: '1 / span 2', alignItems: 'stretch' }}>
        <div style={{ display: 'flex', gap: 6 }}>
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#ff5f57' }}></span>
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#febc2e' }}></span>
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#28c840' }}></span>
        </div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--fg-2)', lineHeight: 1.6 }}>
          <div><span style={{ color: 'var(--fg-3)' }}>$</span> ecode deploy --service ecworks</div>
          <div style={{ color: accent }}>→ build complete · 3.4s</div>
          <div><span style={{ color: 'var(--fg-3)' }}>$</span> probe /api/ai</div>
          <div style={{ color: accent }}>200 OK · 412ms</div>
          <div><span style={{ color: 'var(--fg-3)' }}>$</span> agent run digest</div>
          <div style={{ color: 'var(--fg-2)' }}>analyzed 1,284 records<span className="caret" /></div>
        </div>
      </div>
      {/* AI ops */}
      <div style={{ ...card, gridColumn: '5 / span 2', gridRow: '1 / span 1' }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.18em' }}>AI OPS / 24h</div>
        <LiveBar accent={accent} label="GPT calls" value={62} target={78} />
        <LiveBar accent={accent} label="Claude" value={41} target={55} />
        <LiveBar accent={accent} label="Speech AI" value={28} target={36} />
      </div>
      {/* Counter */}
      <div style={{ ...card, gridColumn: '5 / span 2', gridRow: '2 / span 1' }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.18em' }}>SELLERS</div>
        <div style={{ fontSize: 30, fontWeight: 700, color: 'var(--fg)' }}>
          1,0<span style={{ color: accent }}>{(40 + (tick % 9)).toString().padStart(2, '0')}</span>
        </div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--fg-2)' }}>↗ +3 today</div>
      </div>
      {/* Wide row */}
      <div style={{ ...card, gridColumn: '1 / span 4', gridRow: '3 / span 1' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.18em' }}>EVENTS / hour</span>
          <span className="mono" style={{ fontSize: 10, color: accent }}>● realtime</span>
        </div>
        <div style={{ flex: 1, minHeight: 30 }}>
          <MiniSparkline color={'var(--fg-2)'} seed={tick + 5} />
        </div>
      </div>
      {/* Status */}
      <div style={{ ...card, gridColumn: '5 / span 2', gridRow: '3 / span 1', justifyContent: 'space-between' }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.18em' }}>SERVICES</div>
        {['ecworks', 'floworder', 'murmur', 'pyuung'].map(s => (
          <div key={s} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, fontFamily: 'var(--font-mono)' }}>
            <span style={{ color: 'var(--fg-2)' }}>{s}</span>
            <span style={{ color: accent }}>● live</span>
          </div>
        ))}
      </div>
      {/* Bottom logs */}
      <div style={{ ...card, gridColumn: '1 / span 6', gridRow: '4 / span 1', flexDirection: 'row', alignItems: 'center', gap: 24, overflow: 'hidden' }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.18em', flexShrink: 0 }}>LOG</div>
        <div style={{ overflow: 'hidden', position: 'relative', flex: 1 }}>
          <div className="mono" style={{ fontSize: 11, color: 'var(--fg-2)', whiteSpace: 'nowrap', display: 'flex', gap: 36, animation: 'marquee 50s linear infinite' }}>
            {Array.from({length: 2}).map((_, i) => (
              <React.Fragment key={i}>
                <span>· 02:14 inference batch /korean-tutor 412ms</span>
                <span>· 02:14 floworder · settlement reconciled</span>
                <span style={{ color: accent }}>· 02:14 ecworks · slack agent dispatched</span>
                <span>· 02:13 murmur · STT pipeline ok</span>
                <span>· 02:13 pyuung · 12 letters queued</span>
                <span style={{ color: accent }}>· 02:13 deploy · cloudflare edge · revision 1ac7</span>
              </React.Fragment>
            ))}
          </div>
        </div>
      </div>
      {/* Overlay fade */}
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', background: `radial-gradient(ellipse 55% 45% at 50% 45%, transparent 0%, var(--bg) 75%)` }} />
    </div>
  );
}

window.HeroCodeFlow = HeroCodeFlow;
window.HeroNeural = HeroNeural;
window.HeroBento = HeroBento;
