// hero.jsx — Hero with animated SVG wave + telemetry
const { useEffect, useRef, useState } = React;

/* ============================================================
   Animated Wave — multi-layered SVG, magenta→purple gradient
   strokes oscillating gently. Uses requestAnimationFrame.
   ============================================================ */
function AnimatedWave({ motion = true }) {
  const ref = useRef(null);
  const rafRef = useRef(0);

  useEffect(() => {
    if (!motion) return;
    const paths = ref.current?.querySelectorAll('.wave-path');
    if (!paths) return;

    const start = performance.now();
    const tick = (now) => {
      const t = (now - start) / 1000;
      paths.forEach((p, i) => {
        const ph = i * 0.6;
        const dy = Math.sin(t * 0.5 + ph) * 6;
        const dx = Math.cos(t * 0.35 + ph) * 4;
        p.setAttribute('transform', `translate(${dx} ${dy})`);
      });
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [motion]);

  // Generate a smooth wave path
  const wave = (yOffset, amp, freq, phase) => {
    const w = 1600;
    const segs = 24;
    let d = `M -100 ${yOffset}`;
    for (let i = 0; i <= segs; i++) {
      const x = (i / segs) * (w + 200) - 100;
      const y = yOffset + Math.sin(i * freq + phase) * amp;
      d += ` L ${x.toFixed(1)} ${y.toFixed(1)}`;
    }
    return d;
  };

  // Generate 18 wave lines with subtle variations
  const lines = [];
  const baseY = 540;
  for (let i = 0; i < 22; i++) {
    const yOffset = baseY + (i - 11) * 14;
    const amp = 28 + Math.sin(i * 0.5) * 12;
    const freq = 0.32 + (i % 5) * 0.04;
    const phase = i * 0.45;
    const opacity = 0.18 + (1 - Math.abs(i - 11) / 11) * 0.55;
    lines.push({ d: wave(yOffset, amp, freq, phase), opacity, i });
  }

  return (
    <svg ref={ref} viewBox="0 0 1600 900" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
      <defs>
        <linearGradient id="waveGrad" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stopColor="#F51EE1" stopOpacity="0" />
          <stop offset="15%" stopColor="#F51EE1" stopOpacity="0.85" />
          <stop offset="50%" stopColor="#A41AE1" stopOpacity="1" />
          <stop offset="85%" stopColor="#6419E1" stopOpacity="0.85" />
          <stop offset="100%" stopColor="#6419E1" stopOpacity="0" />
        </linearGradient>
        <linearGradient id="waveGrad2" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stopColor="#F51EE1" stopOpacity="0" />
          <stop offset="50%" stopColor="#F51EE1" stopOpacity="0.5" />
          <stop offset="100%" stopColor="#6419E1" stopOpacity="0" />
        </linearGradient>
        <filter id="waveGlow" x="-10%" y="-10%" width="120%" height="120%">
          <feGaussianBlur stdDeviation="0.8" />
        </filter>
      </defs>
      {lines.map((l) => (
        <path
          key={l.i}
          className="wave-path"
          d={l.d}
          fill="none"
          stroke={l.i === 11 ? "url(#waveGrad2)" : "url(#waveGrad)"}
          strokeWidth={l.i === 11 ? 2.5 : 1}
          strokeOpacity={l.opacity}
          strokeLinecap="round"
          filter={l.i === 11 ? "url(#waveGlow)" : undefined}
        />
      ))}
    </svg>
  );
}

/* ============================================================
   Gradient Mesh hero variant — large rotating gradient blob
   ============================================================ */
function GradientMesh({ motion = true }) {
  return (
    <svg viewBox="0 0 1600 900" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
      <defs>
        <radialGradient id="m1" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#F51EE1" stopOpacity="0.55" />
          <stop offset="100%" stopColor="#F51EE1" stopOpacity="0" />
        </radialGradient>
        <radialGradient id="m2" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#6419E1" stopOpacity="0.55" />
          <stop offset="100%" stopColor="#6419E1" stopOpacity="0" />
        </radialGradient>
        <filter id="meshBlur" x="-20%" y="-20%" width="140%" height="140%">
          <feGaussianBlur stdDeviation="60" />
        </filter>
      </defs>
      <g filter="url(#meshBlur)">
        <circle cx="500" cy="500" r="420" fill="url(#m1)">
          {motion && <animate attributeName="cx" values="500;700;500" dur="14s" repeatCount="indefinite" />}
        </circle>
        <circle cx="1100" cy="400" r="380" fill="url(#m2)">
          {motion && <animate attributeName="cy" values="400;560;400" dur="18s" repeatCount="indefinite" />}
        </circle>
      </g>
    </svg>
  );
}

/* ============================================================
   Animated counter — counts up on viewport enter
   ============================================================ */
function Count({ to, suffix = '', prefix = '', duration = 1600, motion = true }) {
  const [val, setVal] = useState(motion ? 0 : to);
  const ref = useRef(null);
  const started = useRef(false);

  useEffect(() => {
    if (!motion) { setVal(to); return; }
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min((now - start) / duration, 1);
            const eased = 1 - Math.pow(1 - t, 3);
            setVal(Math.round(to * eased));
            if (t < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [to, duration, motion]);

  return <span ref={ref}>{prefix}{val}{suffix}</span>;
}

function Hero({ tweaks }) {
  const { heroVariant = 'wave', motion = true } = tweaks || {};
  const [time, setTime] = useState('');

  useEffect(() => {
    const fmt = () => {
      const d = new Date();
      const hh = String(d.getUTCHours()).padStart(2, '0');
      const mm = String(d.getUTCMinutes()).padStart(2, '0');
      const ss = String(d.getUTCSeconds()).padStart(2, '0');
      setTime(`${hh}:${mm}:${ss} UTC`);
    };
    fmt();
    const id = setInterval(fmt, 1000);
    return () => clearInterval(id);
  }, []);

  return (
    <section className="hero" id="top">
      <div className="hero__bg" />
      <div className="hero__grid-overlay" />
      <div className="hero__wave">
        {heroVariant === 'mesh' ? <GradientMesh motion={motion} /> : <AnimatedWave motion={motion} />}
      </div>

      <div className="hero__ticker">
        <div className="row"><span className="dot" /> SYSTEM ONLINE</div>
        <div className="row">MÖNCHENGLADBACH, DE</div>
        <div className="row">51.18°N · 6.43°E</div>
        <div className="row">{time}</div>
        <div className="row">v.26.05 // BUILD STABLE</div>
      </div>

      <div className="container hero__inner">
        <div className="hero__topline">
          <span className="dot" />
          <span className="mono">AI infrastructure for real-world systems</span>
        </div>

        <h1 className="hero__title">
          From <span className="it">simulation</span><br />
          to <span className="it">deployment.</span>
        </h1>

        <p className="hero__sub">
          Mindwaves builds Digital Twins, Autonomous Laboratories, and Edge AI — operational infrastructure for industrial, biological, and physical systems. Not dashboards. Decision infrastructure.
        </p>

        <div className="hero__actions">
          <a href="#contact" data-action="contact" className="btn btn--primary">
            Start a conversation
            <i data-lucide="arrow-up-right"></i>
          </a>
          <a href="#services" className="btn btn--ghost">
            Explore systems
            <i data-lucide="arrow-right"></i>
          </a>
        </div>

        <div className="hero__telemetry">
          <div className="tele-item">
            <span className="tele-item__num"><span className="grad"><Count to={9} motion={motion} /></span></span>
            <span className="tele-item__lbl">Core systems</span>
          </div>
          <div className="tele-item">
            <span className="tele-item__num"><Count to={9} suffix="+" motion={motion} /></span>
            <span className="tele-item__lbl">Industry verticals</span>
          </div>
          <div className="tele-item">
            <span className="tele-item__num">BAFA</span>
            <span className="tele-item__lbl">Accredited advisor</span>
          </div>
          <div className="tele-item">
            <span className="tele-item__num"><Count to={100} suffix="ms" prefix="<" motion={motion} /></span>
            <span className="tele-item__lbl">Edge inference latency</span>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, Count, AnimatedWave, GradientMesh });
