// Hero — peristaltic biological motion canvas
const { useEffect, useRef, useState } = React;

function PeristalticCanvas({ theme }) {
  const canvasRef = useRef(null);
  const mouseRef = useRef({ x: 0.5, y: 0.5, tx: 0.5, ty: 0.5 });

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let raf, w, h, dpr;

    const resize = () => {
      dpr = Math.min(window.devicePixelRatio || 1, 2);
      const rect = canvas.getBoundingClientRect();
      w = rect.width; h = rect.height;
      canvas.width = w * dpr; canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    window.addEventListener('resize', resize);

    const onMove = (e) => {
      const rect = canvas.getBoundingClientRect();
      mouseRef.current.tx = (e.clientX - rect.left) / rect.width;
      mouseRef.current.ty = (e.clientY - rect.top) / rect.height;
    };
    window.addEventListener('mousemove', onMove);

    const palette = theme === 'dark'
      ? { bg: '#0a0e0c', wave: 'rgba(212, 223, 183, ', glow: 'rgba(201, 232, 163, ', deep: 'rgba(168, 193, 148, ' }
      : { bg: '#f0ebe1', wave: 'rgba(26, 58, 42, ', glow: 'rgba(45, 87, 64, ', deep: 'rgba(107, 162, 126, ' };

    let t = 0;
    const draw = () => {
      t += 0.005;
      // ease mouse
      mouseRef.current.x += (mouseRef.current.tx - mouseRef.current.x) * 0.05;
      mouseRef.current.y += (mouseRef.current.ty - mouseRef.current.y) * 0.05;
      const mx = mouseRef.current.x, my = mouseRef.current.y;

      // clear with subtle fade for trail
      ctx.fillStyle = theme === 'dark' ? 'rgba(10,14,12,0.12)' : 'rgba(240,235,225,0.12)';
      ctx.fillRect(0, 0, w, h);

      // peristaltic flowing waves — concentric organic ribbons
      const cx = w * (0.55 + (mx - 0.5) * 0.15);
      const cy = h * (0.5 + (my - 0.5) * 0.1);

      const layers = 22;
      for (let l = 0; l < layers; l++) {
        const phase = t + l * 0.18;
        const baseR = 60 + l * 24;
        ctx.beginPath();
        const steps = 220;
        for (let i = 0; i <= steps; i++) {
          const a = (i / steps) * Math.PI * 2;
          // peristaltic squeeze: multi-wave radial deformation
          const sq1 = Math.sin(a * 3 + phase * 1.3) * 18;
          const sq2 = Math.sin(a * 5 - phase * 0.7) * 10;
          const sq3 = Math.sin(a * 2 + phase * 0.5 + l * 0.4) * 26;
          // mouse warp
          const dx = Math.cos(a), dy = Math.sin(a);
          const mxw = (mx - 0.5) * 120 * Math.cos(a + phase * 0.3);
          const myw = (my - 0.5) * 80 * Math.sin(a - phase * 0.2);
          const r = baseR + sq1 + sq2 + sq3;
          const x = cx + dx * r + mxw * (l / layers);
          const y = cy + dy * r * 0.62 + myw * (l / layers);
          if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
        }
        ctx.closePath();
        const fade = Math.pow(1 - l / layers, 1.4);
        const alpha = 0.04 + fade * 0.10;
        ctx.strokeStyle = (l % 3 === 0 ? palette.glow : palette.wave) + alpha + ')';
        ctx.lineWidth = 1 + (l % 4 === 0 ? 0.5 : 0);
        ctx.stroke();
      }

      // bright moving nucleus
      const grd = ctx.createRadialGradient(cx, cy, 0, cx, cy, 280);
      grd.addColorStop(0, palette.glow + '0.32)');
      grd.addColorStop(0.5, palette.deep + '0.10)');
      grd.addColorStop(1, palette.wave + '0)');
      ctx.fillStyle = grd;
      ctx.fillRect(0, 0, w, h);

      // particles drifting
      const pCount = 40;
      for (let i = 0; i < pCount; i++) {
        const a = (i / pCount) * Math.PI * 2 + t * 0.4;
        const r = 80 + ((i * 17) % 360) + Math.sin(t + i) * 30;
        const x = cx + Math.cos(a) * r;
        const y = cy + Math.sin(a) * r * 0.62;
        ctx.beginPath();
        ctx.arc(x, y, 1 + (i % 3) * 0.5, 0, Math.PI * 2);
        ctx.fillStyle = palette.glow + (0.3 + (i % 5) * 0.1) + ')';
        ctx.fill();
      }

      raf = requestAnimationFrame(draw);
    };
    draw();

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', resize);
      window.removeEventListener('mousemove', onMove);
    };
  }, [theme]);

  return <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }} />;
}

function Hero({ theme }) {
  const [time, setTime] = useState('');
  useEffect(() => {
    const update = () => {
      const d = new Date();
      const t = d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: 'America/Los_Angeles' });
      setTime(t + ' PT');
    };
    update();
    const id = setInterval(update, 30000);
    return () => clearInterval(id);
  }, []);

  return (
    <section className="hero">
      <PeristalticCanvas theme={theme} />
      <div className="hero-vignette" />
      <div className="hero-grid" />

      <div className="hero-top container">
        <a href="https://apps.apple.com/us/app/gutsy-ai-ibs-trigger-finder/id6758587496" target="_blank" rel="noopener noreferrer" className="app-capsule" aria-label="Download on the App Store">
          <span className="ac-orb">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true">
              <path d="M17.05 12.04c-.03-3.18 2.6-4.7 2.72-4.78-1.48-2.16-3.79-2.46-4.61-2.49-1.96-.2-3.83 1.15-4.83 1.15-1.01 0-2.55-1.13-4.19-1.1-2.16.03-4.15 1.25-5.26 3.18C-1.39 12-.07 17.46 2.16 20.46c1.1 1.47 2.41 3.13 4.13 3.07 1.66-.07 2.29-1.07 4.29-1.07 2 0 2.57 1.07 4.32 1.04 1.78-.03 2.91-1.5 4-2.98 1.26-1.71 1.78-3.37 1.81-3.45-.04-.02-3.47-1.34-3.5-5.32zm-3.18-9.78C14.79 1.16 15.4-.34 15.21-1.84c-1.27.05-2.81.85-3.74 1.93-.83.96-1.57 2.5-1.37 3.96 1.42.11 2.86-.72 3.77-1.79z"/>
            </svg>
          </span>
          <span className="ac-text">
            <span className="ac-pre cap">Now Available</span>
            <span className="ac-main">Download on the <em className="serif-it">App Store</em></span>
          </span>
          <span className="ac-arr" aria-hidden="true">
            <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
              <path d="M3 8h10M9 4l4 4-4 4" />
            </svg>
          </span>
          <span className="ac-shine" />
        </a>
      </div>

      <div className="hero-mid container">
        <h1 className="hero-title serif">
          <span className="hl-1">Go with</span><br />
          <span className="hl-2">your <em className="serif-it">gut.</em></span>
        </h1>
        <div className="hero-sub">
          <p>Six weeks. Real evidence.<br />Your gut, finally <em className="serif-it">understood.</em></p>
        </div>
        <div className="hero-cta">
          <a href="https://apps.apple.com/us/app/gutsy-ai-ibs-trigger-finder/id6758587496" target="_blank" rel="noopener noreferrer" className="btn">
            <span>Begin Your Protocol</span>
            <span className="arr">→</span>
          </a>
          <div className="hero-meta">
            <div><span className="cap">07d</span> free trial</div>
            <div className="sep" />
            <div><span className="cap">No</span> credit card</div>
            <div className="sep" />
            <div><span className="cap">iOS</span> 17.0+</div>
          </div>
        </div>
      </div>

      <div className="hero-bottom container">
        <div className="hero-stats">
          <div className="hstat">
            <div className="hstat-num serif">5<span className="star">★</span></div>
            <div className="cap">App Store</div>
          </div>
          <div className="hstat">
            <div className="hstat-num serif">10<span className="unit">+</span></div>
            <div className="cap">Clinical research reports</div>
          </div>
          <div className="hstat">
            <div className="hstat-num serif">Rx</div>
            <div className="cap">Doctor recommended</div>
          </div>
          <div className="hstat">
            <div className="hstat-num serif">100<span className="unit">%</span></div>
            <div className="cap">On-device privacy</div>
          </div>
        </div>
        <div className="hero-scroll">
          <span className="cap">Scroll</span>
          <span className="line" />
        </div>
      </div>

      <style>{`
        .hero {
          position: relative;
          height: 100vh;
          min-height: 760px;
          background: var(--bg);
          overflow: hidden;
          display: flex;
          flex-direction: column;
        }
        .hero-vignette {
          position: absolute; inset: 0;
          background: radial-gradient(ellipse at center, transparent 30%, var(--bg) 95%);
          pointer-events: none; z-index: 1;
        }
        .hero-grid {
          position: absolute; inset: 0;
          background-image: linear-gradient(var(--line-2) 1px, transparent 1px), linear-gradient(90deg, var(--line-2) 1px, transparent 1px);
          background-size: 80px 80px;
          mask-image: radial-gradient(ellipse at center, transparent 30%, black 90%);
          opacity: 0.5;
          pointer-events: none; z-index: 1;
        }
        .hero-top, .hero-mid, .hero-bottom {
          position: relative; z-index: 2;
        }
        .hero-top {
          display: flex; justify-content: center; align-items: center;
          padding-top: 110px;
        }
        .hero-tag { display: inline-flex; align-items: center; gap: 10px; color: var(--muted); }
        .hero-tag-r { color: var(--muted); }
        .dot-live {
          width: 6px; height: 6px; border-radius: 50%;
          background: var(--accent-glow);
          box-shadow: 0 0 12px var(--accent-glow);
          animation: pulse 2s ease-in-out infinite;
        }
        @keyframes pulse { 0%, 100% { opacity: 0.6; } 50% { opacity: 1; } }

        .app-capsule {
          position: relative;
          display: inline-flex; align-items: center; gap: 12px;
          padding: 9px 16px 9px 9px;
          border-radius: 999px;
          background: color-mix(in oklab, var(--ink) 92%, transparent);
          color: var(--bg);
          text-decoration: none;
          overflow: hidden;
          isolation: isolate;
          border: 1px solid color-mix(in oklab, var(--ink) 100%, transparent);
          box-shadow:
            0 1px 0 0 rgba(255,255,255,0.06) inset,
            0 12px 30px -12px rgba(20,40,30,0.45),
            0 0 0 0.5px color-mix(in oklab, var(--accent) 40%, transparent);
          transition: transform 0.4s cubic-bezier(0.2,0.8,0.2,1), box-shadow 0.4s;
        }
        .app-capsule::before {
          content: "";
          position: absolute; inset: 0;
          border-radius: inherit;
          background: linear-gradient(135deg, color-mix(in oklab, var(--accent) 30%, transparent) 0%, transparent 45%, color-mix(in oklab, var(--accent-glow) 25%, transparent) 100%);
          opacity: 0.55;
          z-index: -1;
        }
        .app-capsule:hover {
          transform: translateY(-1px);
          box-shadow:
            0 1px 0 0 rgba(255,255,255,0.08) inset,
            0 18px 40px -10px rgba(20,40,30,0.55),
            0 0 0 1px color-mix(in oklab, var(--accent) 60%, transparent);
        }
        .ac-orb {
          width: 28px; height: 28px; border-radius: 50%;
          display: inline-flex; align-items: center; justify-content: center;
          background: radial-gradient(circle at 30% 30%, color-mix(in oklab, var(--accent-glow) 70%, white) 0%, var(--accent) 60%, color-mix(in oklab, var(--accent) 70%, black) 100%);
          color: var(--bg);
          box-shadow: 0 0 12px color-mix(in oklab, var(--accent-glow) 60%, transparent), 0 1px 0 0 rgba(255,255,255,0.15) inset;
          flex-shrink: 0;
        }
        .ac-text { display: inline-flex; flex-direction: column; line-height: 1.05; }
        .ac-pre {
          font-size: 9px;
          letter-spacing: 0.22em;
          color: color-mix(in oklab, var(--bg) 60%, transparent);
          margin-bottom: 2px;
        }
        .ac-main {
          font-size: 13px;
          font-weight: 500;
          letter-spacing: -0.01em;
          color: var(--bg);
        }
        .ac-main em {
          color: color-mix(in oklab, var(--accent-glow) 80%, white);
          font-weight: 400;
        }
        .ac-arr {
          width: 22px; height: 22px; border-radius: 50%;
          display: inline-flex; align-items: center; justify-content: center;
          background: color-mix(in oklab, var(--bg) 12%, transparent);
          color: var(--bg);
          margin-left: 2px;
          transition: transform 0.4s cubic-bezier(0.2,0.8,0.2,1), background 0.3s;
        }
        .app-capsule:hover .ac-arr {
          transform: translateX(3px);
          background: color-mix(in oklab, var(--accent-glow) 50%, transparent);
        }
        .ac-shine {
          position: absolute; top: 0; left: -40%;
          width: 30%; height: 100%;
          background: linear-gradient(90deg, transparent, rgba(255,255,255,0.18), transparent);
          transform: skewX(-20deg);
          animation: capsuleShine 5s ease-in-out infinite;
          pointer-events: none;
        }
        @keyframes capsuleShine {
          0%, 70% { left: -40%; }
          100% { left: 140%; }
        }
          box-shadow: 0 0 0 0 var(--accent-glow);
          animation: pulse 2s infinite;
        }
        @keyframes pulse {
          0%, 100% { box-shadow: 0 0 0 0 rgba(107,162,126,0.6); }
          50% { box-shadow: 0 0 0 8px rgba(107,162,126,0); }
        }

        .hero-mid {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          padding-top: 40px;
        }
        .hero-eyebrow { margin-bottom: 32px; }
        .hero-title {
          font-size: clamp(72px, 13vw, 220px);
          line-height: 0.92;
          letter-spacing: -0.04em;
          font-weight: 300;
          color: var(--ink);
        }
        .hero-title .hl-1 { display: inline-block; }
        .hero-title .hl-2 { display: inline-block; }
        .hero-title em { color: var(--accent); }
        [data-theme="dark"] .hero-title em { color: var(--accent-glow); }
        .hero-sub {
          margin-top: 36px;
          max-width: 480px;
          font-size: 20px;
          line-height: 1.4;
          color: var(--ink-2);
          font-weight: 300;
        }
        .hero-sub em { color: var(--accent); }
        [data-theme="dark"] .hero-sub em { color: var(--accent-glow); }

        .hero-cta {
          margin-top: 48px;
          display: flex;
          align-items: center;
          gap: 32px;
          flex-wrap: wrap;
        }
        .hero-meta {
          display: flex; align-items: center; gap: 18px;
          color: var(--muted);
          font-size: 13px;
        }
        .hero-meta .cap { color: var(--ink); }
        .hero-meta .sep { width: 1px; height: 14px; background: var(--line); }

        .hero-bottom {
          padding-bottom: 48px;
          display: flex; justify-content: space-between; align-items: flex-end;
          gap: 40px;
        }
        .hero-stats {
          display: grid;
          grid-template-columns: repeat(4, auto);
          gap: 44px;
          align-items: end;
        }
        .hstat-num {
          font-family: 'Fraunces', serif;
          font-weight: 300;
          font-size: 40px;
          line-height: 1;
          color: var(--ink);
          letter-spacing: -0.04em;
        }
        .hstat-num .star { font-size: 22px; color: var(--accent); margin-left: 4px; vertical-align: super; }
        .hstat-num .unit { font-size: 18px; color: var(--muted); margin-left: 4px; }
        .hstat .cap { color: var(--muted); margin-top: 8px; display: block; font-size: 10px; }

        .hero-scroll {
          display: flex; flex-direction: column; align-items: center; gap: 12px;
          color: var(--muted);
        }
        .hero-scroll .line {
          width: 1px; height: 60px;
          background: linear-gradient(to bottom, transparent, var(--ink) 40%, transparent);
          animation: scrollPulse 2.5s ease-in-out infinite;
        }
        @keyframes scrollPulse {
          0%, 100% { transform: scaleY(0.4); transform-origin: top; }
          50% { transform: scaleY(1); }
        }

        @media (max-width: 900px) {
          .hero-stats { grid-template-columns: repeat(2, 1fr); gap: 28px; }
          .hero-bottom { flex-direction: column; align-items: flex-start; }
          .hero-scroll { display: none; }
        }
      `}</style>
    </section>
  );
}

window.Hero = Hero;
