// Hero v6, Full light/dark adaptive, time-based metrics, award-winning canvas design
const { useState: useHeroState, useEffect: useHeroEffect, useRef: useHeroRef } = React;

// ─── Agent network data (module-level, never recreated) ──────────────────────
const H_NODES = [
  { x: 0.38, y: 0.50, r: 6,  c: [0,217,160],  label: 'TRIGGER'      },
  { x: 0.55, y: 0.50, r: 13, c: [0,217,160],  label: 'ORCHESTRATOR', hub: true },
  { x: 0.67, y: 0.27, r: 7,  c: [139,92,246], label: 'CLASSIFIER'   },
  { x: 0.67, y: 0.50, r: 7,  c: [139,92,246], label: 'MEMORY'       },
  { x: 0.67, y: 0.73, r: 7,  c: [139,92,246], label: 'TOOL CALLER'  },
  { x: 0.80, y: 0.21, r: 5,  c: [245,158,11], label: 'CRM'          },
  { x: 0.80, y: 0.43, r: 5,  c: [245,158,11], label: 'CALENDAR'     },
  { x: 0.80, y: 0.65, r: 5,  c: [245,158,11], label: 'EMAIL/SMS'    },
  { x: 0.72, y: 0.83, r: 6,  c: [0,217,160],  label: 'VALIDATOR'    },
  { x: 0.54, y: 0.82, r: 6,  c: [0,217,160],  label: 'RESPONSE'     },
];
const H_EDGES = [
  { f:0, t:1, c:[0,217,160]  }, { f:1, t:2, c:[0,217,160]  },
  { f:1, t:3, c:[0,217,160]  }, { f:1, t:4, c:[0,217,160]  },
  { f:2, t:5, c:[139,92,246] }, { f:3, t:6, c:[139,92,246] },
  { f:4, t:7, c:[139,92,246] }, { f:5, t:8, c:[245,158,11] },
  { f:6, t:8, c:[245,158,11] }, { f:7, t:8, c:[245,158,11] },
  { f:8, t:9, c:[0,217,160]  }, { f:9, t:1, c:[0,217,160],  feedback: true },
];
const H_PKTS = [
  { e:0,  spd:0.18, off:0.00 }, { e:0,  spd:0.18, off:0.55 },
  { e:1,  spd:0.22, off:0.10 }, { e:2,  spd:0.20, off:0.42 },
  { e:3,  spd:0.16, off:0.72 }, { e:4,  spd:0.25, off:0.20 },
  { e:5,  spd:0.23, off:0.50 }, { e:6,  spd:0.21, off:0.80 },
  { e:7,  spd:0.28, off:0.15 }, { e:8,  spd:0.27, off:0.46 },
  { e:9,  spd:0.26, off:0.75 }, { e:10, spd:0.19, off:0.30 },
  { e:11, spd:0.11, off:0.08 },
];
// Rotating last word in headline, speaks to every vertical
const H_WORDS = ['business.', 'pipeline.', 'clinic.', 'firm.', 'brokerage.', 'practice.', 'brand.'];

const H_ACTS = [
  [
    { t:'trigger', m:'Lead signal via API webhook'          },
    { t:'process', m:'Intent enrichment, 5 data sources'  },
    { t:'process', m:'Email crafted · persona: VP Sales'    },
    { t:'success', m:'CRM updated · reply routed to AE ✓'  },
  ],
  [
    { t:'trigger', m:'Booking request · Med Spa client'     },
    { t:'process', m:'Calendar availability synced'         },
    { t:'process', m:'Confirmation: SMS + email dispatched' },
    { t:'success', m:'Intake form pre-filled · delivered ✓' },
  ],
  [
    { t:'trigger', m:'Invoice 30+ days overdue flagged'     },
    { t:'process', m:'Payment reminder sequence started'    },
    { t:'process', m:'Link opened · 3 min after send'       },
    { t:'success', m:'Payment received · QuickBooks synced ✓'},
  ],
  [
    { t:'trigger', m:'New job order · staffing client'      },
    { t:'process', m:'Candidate scoring pipeline running'   },
    { t:'process', m:'Top 3 matched · Calendly links sent'  },
    { t:'success', m:'Interview confirmed · 0 human touch ✓'},
  ],
];

// ─── Theme tokens (pure function, no React deps) ─────────────────────────────
function heroTheme(isDark) {
  const d = isDark;
  return {
    sectionBg:    d ? '#0C0E14'  : '#F5F5FA',
    bloomBg:      d
      ? 'radial-gradient(ellipse 55% 70% at 68% 47%, rgba(0,217,160,0.06) 0%, rgba(139,92,246,0.04) 45%, transparent 70%)'
      : 'radial-gradient(ellipse 55% 70% at 68% 47%, rgba(0,140,110,0.06) 0%, rgba(99,61,200,0.04) 45%, transparent 70%)',
    leftFade:     d
      ? 'linear-gradient(to right, #0C0E14 0%, #0C0E14 22%, rgba(12,14,20,0.75) 48%, transparent 68%)'
      : 'linear-gradient(to right, #F5F5FA 0%, #F5F5FA 22%, rgba(245,245,250,0.78) 48%, transparent 68%)',
    // Badge
    badgeBg:      d ? 'rgba(0,217,160,0.09)'    : 'rgba(0,130,100,0.08)',
    badgeBdr:     d ? 'rgba(0,217,160,0.28)'    : 'rgba(0,130,100,0.32)',
    badgeTxt:     d ? '#00D9A0'                 : '#007A5A',
    // Headline
    h1Txt:        d ? '#F0F2F5'                 : '#0A0A12',
    gradTxt:      d
      ? 'linear-gradient(120deg, #00D9A0 0%, #6BFFD0 50%, #00D9A0 100%)'
      : 'linear-gradient(120deg, #007A5A 0%, #00A077 50%, #007A5A 100%)',
    subTxt:       d ? 'rgba(240,242,245,0.58)'  : 'rgba(10,10,18,0.6)',
    subStrong:    d ? 'rgba(240,242,245,0.88)'  : '#0A0A12',
    // Ghost CTA
    ctaGhostBg:   d ? 'rgba(255,255,255,0.05)'  : 'rgba(10,10,18,0.04)',
    ctaGhostTxt:  d ? 'rgba(240,242,245,0.78)'  : 'rgba(10,10,18,0.75)',
    ctaGhostBdr:  d ? 'rgba(255,255,255,0.12)'  : 'rgba(10,10,18,0.2)',
    ctaGhostHover:d ? 'rgba(255,255,255,0.1)'   : 'rgba(10,10,18,0.08)',
    ctaBdrHover:  d ? 'rgba(0,217,160,0.4)'     : 'rgba(0,130,100,0.45)',
    // Stats
    statMint:     d ? '#00D9A0' : '#007A5A',
    statViolet:   d ? '#8B5CF6' : '#4828CC',
    statAmber:    d ? '#F59E0B' : '#B45309',
    statLbl:      d ? 'rgba(240,242,245,0.33)'  : 'rgba(10,10,18,0.5)',
    statDivBg:    d ? 'rgba(255,255,255,0.09)'  : 'rgba(10,10,18,0.14)',
    // Activity card
    cardBg:       d ? 'rgba(14,16,24,0.86)'     : 'rgba(255,255,255,0.88)',
    cardBdr:      d ? 'rgba(255,255,255,0.09)'  : 'rgba(10,10,18,0.1)',
    cardShadow:   d
      ? '0 32px 80px rgba(0,0,0,0.55), 0 0 0 1px rgba(255,255,255,0.04), inset 0 1px 0 rgba(255,255,255,0.05)'
      : '0 24px 60px rgba(0,0,0,0.1), 0 0 0 1px rgba(255,255,255,0.8), inset 0 1px 0 rgba(255,255,255,0.9)',
    cardHdrBg:    d ? 'rgba(255,255,255,0.025)' : 'rgba(10,10,18,0.03)',
    cardHdrBdr:   d ? 'rgba(255,255,255,0.07)'  : 'rgba(10,10,18,0.08)',
    cardMonoTxt:  d ? 'rgba(255,255,255,0.28)'  : 'rgba(10,10,18,0.45)',
    cardSecTxt:   d ? 'rgba(255,255,255,0.22)'  : 'rgba(10,10,18,0.4)',
    cardLbl:      d ? 'rgba(255,255,255,0.2)'   : 'rgba(10,10,18,0.42)',
    cardDivider:  d ? 'rgba(255,255,255,0.06)'  : 'rgba(10,10,18,0.08)',
    processTxt:   d ? 'rgba(240,242,245,0.55)'  : 'rgba(10,10,18,0.7)',
    successTxt:   d ? '#00D9A0'                 : '#007A5A',
    trigTxt:      d ? '#8B5CF6'                 : '#4828CC',
    // Ticker
    tickerBg:     d ? 'rgba(12,14,20,0.88)'     : 'rgba(245,245,250,0.94)',
    tickerBdr:    d ? 'rgba(255,255,255,0.07)'  : 'rgba(10,10,18,0.1)',
    tickerTxt:    d ? 'rgba(255,255,255,0.28)'  : 'rgba(10,10,18,0.45)',
    tickerDot:    d ? '#00D9A0'                 : '#007A5A',
    tickerDotOp:  d ? 0.38                      : 0.5,
    // Canvas-specific params
    canvas: {
      gridRGB:    d ? [255,255,255] : [0,0,20],
      gridLineA:  d ? (x,W) => 0.013 + (x/W)*0.018 : (x,W) => 0.038 + (x/W)*0.042,
      gridHLineA: d ? 0.013 : 0.028,
      dotA:       d ? (x,W) => 0.035 + (x/W)*0.065 : (x,W) => 0.055 + (x/W)*0.1,
      edgeCore:   d ? 0.22  : 0.30,
      edgeGlow:   d ? 0.055 : 0.075,
      pktHalo:    d ? 0.12  : 0.15,
      hubBloom:   d ? 0.16  : 0.12,
      nodeLbl:    d ? 'rgba(255,255,255,0.22)' : 'rgba(0,0,20,0.42)',
      spotlightAlpha: d ? 0.10 : 0.08,
    },
  };
}

// ─── Canvas helpers ───────────────────────────────────────────────────────────
function heroBez(t, ax, ay, bx, by, cx, cy) {
  const u = 1 - t;
  return { x: u*u*ax + 2*u*t*bx + t*t*cx, y: u*u*ay + 2*u*t*by + t*t*cy };
}

function drawHeroCanvas(ctx, W, H, sec, cv, mouse) {
  ctx.clearRect(0, 0, W, H);
  const [gr, gg, gb] = cv.gridRGB;
  const G = 72;

  // Cursor-following ambient mint spotlight, award-winning touch
  if (mouse && mouse.active) {
    const cx = mouse.x * W, cy = mouse.y * H;
    const r1 = 320;
    const grad = ctx.createRadialGradient(cx, cy, 0, cx, cy, r1);
    grad.addColorStop(0,    `rgba(0,217,160,${cv.spotlightAlpha})`);
    grad.addColorStop(0.45, `rgba(139,92,246,${cv.spotlightAlpha * 0.4})`);
    grad.addColorStop(1,    'rgba(0,217,160,0)');
    ctx.fillStyle = grad;
    ctx.fillRect(cx - r1, cy - r1, r1 * 2, r1 * 2);
  }

  // ── Grid lines ────────────────────────────────────────────────────────────
  ctx.lineWidth = 0.55;
  for (let x = 0; x <= W; x += G) {
    const a = cv.gridLineA(x, W);
    ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, H);
    ctx.strokeStyle = `rgba(${gr},${gg},${gb},${a})`; ctx.stroke();
  }
  for (let y = 0; y <= H; y += G) {
    ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(W, y);
    ctx.strokeStyle = `rgba(${gr},${gg},${gb},${cv.gridHLineA})`; ctx.stroke();
  }
  // Grid intersection dots
  for (let x = 0; x <= W; x += G) {
    for (let y = 0; y <= H; y += G) {
      const a = cv.dotA(x, W);
      ctx.beginPath(); ctx.arc(x, y, 1, 0, Math.PI * 2);
      ctx.fillStyle = `rgba(${gr},${gg},${gb},${a})`; ctx.fill();
    }
  }

  // ── Edges ─────────────────────────────────────────────────────────────────
  H_EDGES.forEach(edge => {
    const fn = H_NODES[edge.f], tn = H_NODES[edge.t];
    const [r, g, b] = edge.c;
    const fx = fn.x*W, fy = fn.y*H, tx = tn.x*W, ty = tn.y*H;
    const cpx = edge.feedback ? (fx+tx)/2     : (fx+tx)/2 - (ty-fy)*0.15;
    const cpy = edge.feedback ? Math.max(fy,ty) + H*0.13 : (fy+ty)/2 + (tx-fx)*0.15;
    // Glow pass
    ctx.beginPath(); ctx.moveTo(fx,fy); ctx.quadraticCurveTo(cpx,cpy,tx,ty);
    ctx.strokeStyle = `rgba(${r},${g},${b},${cv.edgeGlow})`; ctx.lineWidth = 4; ctx.stroke();
    // Core line
    ctx.beginPath(); ctx.moveTo(fx,fy); ctx.quadraticCurveTo(cpx,cpy,tx,ty);
    ctx.strokeStyle = `rgba(${r},${g},${b},${cv.edgeCore})`; ctx.lineWidth = 0.8; ctx.stroke();
  });

  // ── Data packets ──────────────────────────────────────────────────────────
  H_PKTS.forEach(pkt => {
    const edge = H_EDGES[pkt.e];
    const fn = H_NODES[edge.f], tn = H_NODES[edge.t];
    const [r, g, b] = edge.c;
    const fx = fn.x*W, fy = fn.y*H, tx = tn.x*W, ty = tn.y*H;
    const cpx = edge.feedback ? (fx+tx)/2     : (fx+tx)/2 - (ty-fy)*0.15;
    const cpy = edge.feedback ? Math.max(fy,ty) + H*0.13 : (fy+ty)/2 + (tx-fx)*0.15;
    const progress = (sec * pkt.spd + pkt.off) % 1;
    const { x: px, y: py } = heroBez(progress, fx, fy, cpx, cpy, tx, ty);
    ctx.beginPath(); ctx.arc(px, py, 6, 0, Math.PI*2);
    ctx.fillStyle = `rgba(${r},${g},${b},${cv.pktHalo})`; ctx.fill();
    ctx.beginPath(); ctx.arc(px, py, 2.2, 0, Math.PI*2);
    ctx.fillStyle = `rgba(${r},${g},${b},0.9)`; ctx.fill();
  });

  // ── Nodes ─────────────────────────────────────────────────────────────────
  H_NODES.forEach((node, i) => {
    const nx = node.x*W, ny = node.y*H;
    const [r, g, b] = node.c;
    const pulse = Math.sin(sec * 1.25 + i * 0.88) * 0.5 + 0.5;
    if (node.hub) {
      const grd = ctx.createRadialGradient(nx, ny, 0, nx, ny, node.r * 7);
      grd.addColorStop(0, `rgba(${r},${g},${b},${cv.hubBloom})`);
      grd.addColorStop(1, `rgba(${r},${g},${b},0)`);
      ctx.fillStyle = grd;
      ctx.beginPath(); ctx.arc(nx, ny, node.r*7, 0, Math.PI*2); ctx.fill();
    }
    // Outer pulsing ring
    ctx.beginPath(); ctx.arc(nx, ny, node.r + 5 + pulse * 4.5, 0, Math.PI*2);
    ctx.strokeStyle = `rgba(${r},${g},${b},${0.07 + pulse * 0.07})`;
    ctx.lineWidth = 0.7; ctx.stroke();
    // Node border
    ctx.beginPath(); ctx.arc(nx, ny, node.r, 0, Math.PI*2);
    ctx.strokeStyle = `rgba(${r},${g},${b},${0.48 + pulse * 0.28})`;
    ctx.lineWidth = 1.4; ctx.stroke();
    // Node fill
    ctx.beginPath(); ctx.arc(nx, ny, node.r - 1, 0, Math.PI*2);
    ctx.fillStyle = `rgba(${r},${g},${b},${0.06 + pulse * 0.05})`; ctx.fill();
    // Label
    ctx.font = '500 8px "JetBrains Mono", monospace';
    ctx.fillStyle = cv.nodeLbl; ctx.textAlign = 'center';
    ctx.fillText(node.label, nx, ny + node.r + 14);
  });
}

// ─── Time-based task count ────────────────────────────────────────────────────
// S-curve: 7am = 0 tasks, peaks around 9pm = 312 tasks
function calcTasksToday() {
  const now = new Date();
  const h = now.getHours() + now.getMinutes() / 60;
  const t = Math.max(0, Math.min(1, (h - 7) / 14)); // 7am → 9pm window
  const s = t * t * (3 - 2 * t);                    // smoothstep S-curve
  return Math.floor(s * 312);
}

// ─── Hero Component ───────────────────────────────────────────────────────────
function Hero({ theme }) {
  const isDark  = theme !== 'light';
  const T       = heroTheme(isDark);
  const isMobile = typeof window !== 'undefined' && window.innerWidth <= 768;

  const canvasRef = useHeroRef(null);
  const rafRef    = useHeroRef(null);
  const cvRef     = useHeroRef(T.canvas); // updated via effect when theme changes
  const mouseRef  = useHeroRef({ x: 0.5, y: 0.5, active: false, tx: 0.5, ty: 0.5 });

  const [visible,    setVisible]    = useHeroState(false);
  const [actIdx,     setActIdx]     = useHeroState(0);
  const [logStep,    setLogStep]    = useHeroState(0);
  const [tasksToday, setTasksToday] = useHeroState(() => calcTasksToday());
  const [wordIdx,    setWordIdx]    = useHeroState(0);
  const [mobileWidth, setMobileWidth] = useHeroState(() => typeof window !== 'undefined' ? window.innerWidth : 1024);

  // Track viewport width for responsive switching
  useHeroEffect(() => {
    const handleResize = () => setMobileWidth(window.innerWidth);
    window.addEventListener('resize', handleResize, { passive: true });
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const isSmallScreen = mobileWidth <= 768;

  // Keep canvas theme ref in sync with light/dark toggle
  useHeroEffect(() => { cvRef.current = heroTheme(isDark).canvas; }, [isDark]);

  // Entrance fade-in
  useHeroEffect(() => {
    const id = setTimeout(() => setVisible(true), 100);
    return () => clearTimeout(id);
  }, []);

  // Tasks today, refresh every 60 s so number tracks real time
  useHeroEffect(() => {
    const id = setInterval(() => setTasksToday(calcTasksToday()), 60000);
    return () => clearInterval(id);
  }, []);

  // Rotating word in headline, every 2.4s
  useHeroEffect(() => {
    if (!visible) return;
    const id = setInterval(() => setWordIdx(i => (i + 1) % H_WORDS.length), 2400);
    return () => clearInterval(id);
  }, [visible]);

  // Canvas RAF loop — DISABLED on mobile for performance
  useHeroEffect(() => {
    if (isSmallScreen) return; // Skip canvas entirely on mobile
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const dpr = window.devicePixelRatio || 1;
    const resize = () => {
      canvas.width  = canvas.offsetWidth  * dpr;
      canvas.height = canvas.offsetHeight * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();

    const section = canvas.closest('section');
    const onMove = (e) => {
      const r = canvas.getBoundingClientRect();
      mouseRef.current.tx = (e.clientX - r.left) / r.width;
      mouseRef.current.ty = (e.clientY - r.top)  / r.height;
      mouseRef.current.active = true;
    };
    const onLeave = () => { mouseRef.current.active = false; };
    if (section) {
      section.addEventListener('mousemove', onMove);
      section.addEventListener('mouseleave', onLeave);
    }

    const loop = ts => {
      const m = mouseRef.current;
      m.x += (m.tx - m.x) * 0.08;
      m.y += (m.ty - m.y) * 0.08;
      drawHeroCanvas(ctx, canvas.offsetWidth, canvas.offsetHeight, ts / 1000, cvRef.current, m);
      rafRef.current = requestAnimationFrame(loop);
    };
    rafRef.current = requestAnimationFrame(loop);
    window.addEventListener('resize', resize);
    return () => {
      cancelAnimationFrame(rafRef.current);
      window.removeEventListener('resize', resize);
      if (section) {
        section.removeEventListener('mousemove', onMove);
        section.removeEventListener('mouseleave', onLeave);
      }
    };
  }, [isSmallScreen]);

  // Activity log cycling through 4 workflow demos
  useHeroEffect(() => {
    if (!visible) return;
    const cur = H_ACTS[actIdx];
    const id = setInterval(() => {
      setLogStep(s => {
        if (s >= cur.length - 1) { setActIdx(a => (a + 1) % H_ACTS.length); return 0; }
        return s + 1;
      });
    }, 1800);
    return () => clearInterval(id);
  }, [visible, actIdx]);

  const act    = H_ACTS[actIdx];
  const tStyle = { trigger: T.trigTxt, process: T.processTxt, success: T.successTxt };
  const tIcon  = { trigger: '◈', process: '›', success: '✓' };

  // MOBILE LAYOUT — Clean, centered, no canvas, no activity card
  if (isSmallScreen) {
    return (
      <section id="hero" style={{
        background: T.sectionBg,
        position: 'relative', minHeight: '100svh',
        display: 'flex', flexDirection: 'column', justifyContent: 'flex-start',
        overflow: 'hidden', paddingTop: 0, paddingBottom: 80,
        transition: 'background 0.45s ease',
      }}>
        {/* Subtle gradient bloom only */}
        <div style={{
          position: 'absolute', inset: 0, pointerEvents: 'none',
          background: isDark
            ? 'radial-gradient(ellipse 80% 60% at 50% 40%, rgba(0,217,160,0.07) 0%, rgba(139,92,246,0.04) 50%, transparent 80%)'
            : 'radial-gradient(ellipse 80% 60% at 50% 40%, rgba(0,140,110,0.06) 0%, rgba(99,61,200,0.03) 50%, transparent 80%)',
        }} />

        <div style={{
          maxWidth: 520, margin: '0 auto', padding: '0 24px',
          display: 'flex', flexDirection: 'column', alignItems: 'center',
          textAlign: 'center', position: 'relative', zIndex: 1,
          marginTop: 120, flex: 1,
        }}>
          {/* Badge */}
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '6px 14px', borderRadius: 100,
            background: T.badgeBg, border: `1px solid ${T.badgeBdr}`,
            marginBottom: 24,
            opacity: visible ? 1 : 0,
            transition: 'all 0.5s ease 0.1s',
          }}>
            <span style={{
              width: 6, height: 6, borderRadius: '50%',
              background: T.badgeTxt, boxShadow: `0 0 8px ${T.badgeTxt}`,
              animation: 'hero-blink 1.5s infinite', display: 'inline-block',
            }} />
            <span style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
              color: T.badgeTxt, letterSpacing: '0.12em',
            }}>AI AUTOMATION · B2B</span>
          </div>

          {/* Headline */}
          <h1 style={{
            fontFamily: 'Syne, sans-serif',
            fontSize: 'clamp(36px, 10vw, 52px)',
            fontWeight: 800, lineHeight: 1.12,
            letterSpacing: '-0.03em', marginBottom: 20,
            color: T.h1Txt,
            opacity: visible ? 1 : 0,
            transform: visible ? 'translateY(0)' : 'translateY(20px)',
            transition: 'opacity 0.7s ease 0.2s, transform 0.7s ease 0.2s',
          }}>
            We build the{' '}
            <span style={{
              color: 'transparent',
              backgroundImage: T.gradTxt,
              WebkitBackgroundClip: 'text',
              WebkitTextFillColor: 'transparent',
              backgroundClip: 'text',
            }}>AI systems</span>{' '}
            that run your{' '}
            <span key={wordIdx} style={{
              display: 'inline-block',
              animation: 'hero-word-in 0.5s cubic-bezier(0.16,1,0.3,1)',
            }}>{H_WORDS[wordIdx]}</span>
          </h1>

          {/* Subline */}
          <p style={{
            fontFamily: 'Inter, sans-serif', fontSize: 15,
            color: T.subTxt, lineHeight: 1.7, marginBottom: 32,
            opacity: visible ? 1 : 0,
            transition: 'opacity 0.6s ease 0.5s',
          }}>
            Custom AI agents & automation for med spas, law firms, real estate teams, and B2B operators.{' '}
            <strong style={{ color: T.subStrong, fontWeight: 600 }}>Production-grade, not prototype.</strong>
          </p>

          {/* CTA buttons */}
          <div style={{
            display: 'flex', flexDirection: 'column', gap: 12, width: '100%',
            opacity: visible ? 1 : 0,
            transition: 'opacity 0.5s ease 0.7s',
          }}>
            <a href="https://cal.com/ratan-kumar/ai-automation-startegy-call-with-ratan-quantaeight"
              target="_blank" rel="noopener"
              style={{
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                padding: '16px 28px', background: '#00D9A0',
                color: '#0A0B0E', fontWeight: 700, fontSize: 15,
                fontFamily: 'Inter, sans-serif', borderRadius: 12,
                textDecoration: 'none',
                boxShadow: '0 4px 24px rgba(0,217,160,0.35)',
              }}
            >Book a discovery call →</a>
            <a href="#work"
              style={{
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                padding: '15px 28px',
                background: T.ctaGhostBg, color: T.ctaGhostTxt,
                fontWeight: 500, fontSize: 15, fontFamily: 'Inter, sans-serif',
                borderRadius: 12, textDecoration: 'none',
                border: `1px solid ${T.ctaGhostBdr}`,
              }}
            >See our work →</a>
          </div>

          {/* Stats strip */}
          <div style={{
            marginTop: 40, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
            gap: 0, width: '100%',
            opacity: visible ? 1 : 0, transition: 'opacity 0.6s ease 0.9s',
            borderTop: `1px solid ${T.statDivBg}`, paddingTop: 24,
          }}>
            {[
              { val: '$1.2M',  sub: 'saved in 6mo',     c: T.statMint   },
              { val: '6 wks',  sub: 'to deployed',      c: T.statViolet },
              { val: '99.97%', sub: 'uptime',           c: T.statAmber  },
            ].map((s, i) => (
              <div key={i} style={{ textAlign: 'center', padding: '0 8px', borderRight: i < 2 ? `1px solid ${T.statDivBg}` : 'none' }}>
                <div style={{
                  fontFamily: 'Syne, sans-serif', fontSize: 18, fontWeight: 700,
                  color: s.c, lineHeight: 1, letterSpacing: '-0.02em',
                }}>{s.val}</div>
                <div style={{
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
                  color: T.statLbl, marginTop: 4,
                }}>{s.sub}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Bottom ticker */}
        <div style={{
          position: 'absolute', bottom: 0, left: 0, right: 0,
          borderTop: `1px solid ${T.tickerBdr}`,
          overflow: 'hidden', padding: '11px 0',
          background: T.tickerBg,
        }}>
          <div style={{
            display: 'flex', animation: 'hero-ticker 22s linear infinite',
            whiteSpace: 'nowrap', width: 'max-content',
          }}>
            {[...Array(6)].map((_, rep) =>
              ['Production AI','Fixed Price','Code You Own','No Lock-in','6-Week Delivery','99.97% Uptime'].map((v, i) => (
                <span key={`${rep}-${i}`} style={{
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
                  color: T.tickerTxt, letterSpacing: '0.08em', padding: '0 16px',
                }}>
                  {v}
                  <span style={{ marginLeft: 12, color: T.tickerDot, opacity: T.tickerDotOp }}>+</span>
                </span>
              ))
            )}
          </div>
        </div>

        <style>{`
          @keyframes hero-blink  { 0%,100%{opacity:1} 50%{opacity:0.3} }
          @keyframes hero-ticker { from{transform:translateX(0)} to{transform:translateX(-50%)} }
          @keyframes hero-word-in {
            from { opacity: 0; transform: translateY(14px); filter: blur(4px); }
            to   { opacity: 1; transform: translateY(0);    filter: blur(0); }
          }
        `}</style>
      </section>
    );
  }

  // DESKTOP LAYOUT
  return (
    <section id="hero" style={{
      background: T.sectionBg,
      position: 'relative', minHeight: '100vh',
      display: 'flex', alignItems: 'center',
      overflow: 'hidden', paddingTop: 72,
      transition: 'background 0.45s ease',
    }}>

      {/* Canvas: grid + agent network */}
      <canvas ref={canvasRef} style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none',
      }} />

      {/* Depth bloom */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: T.bloomBg,
        transition: 'background 0.45s ease',
      }} />

      {/* Left-edge fade */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: T.leftFade,
        transition: 'background 0.45s ease',
      }} />

      {/* Content grid */}
      <div style={{
        maxWidth: 1280, margin: '0 auto', padding: '60px 48px 128px',
        display: 'grid', gridTemplateColumns: '55fr 45fr',
        gap: 56, alignItems: 'center', width: '100%', position: 'relative', zIndex: 1,
      }} className="hero-grid">

        {/* ── LEFT: copy ──────────────────────────────────────────────── */}
        <div>
          {/* Badge pill */}
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '6px 16px', borderRadius: 100,
            background: T.badgeBg, border: `1px solid ${T.badgeBdr}`,
            marginBottom: 30,
            opacity: visible ? 1 : 0, transform: visible ? 'translateY(0)' : 'translateY(10px)',
            transition: 'all 0.5s ease 0.1s, background 0.45s ease, border-color 0.45s ease',
          }}>
            <span style={{
              width: 6, height: 6, borderRadius: '50%',
              background: T.badgeTxt, boxShadow: `0 0 8px ${T.badgeTxt}`,
              animation: 'hero-blink 1.5s infinite', display: 'inline-block',
              transition: 'background 0.45s ease',
            }} />
            <span style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
              color: T.badgeTxt, letterSpacing: '0.12em', fontWeight: 500,
              transition: 'color 0.45s ease',
            }}>AI AUTOMATION · B2B</span>
          </div>

          {/* Headline, last line word rotates every 2.4s */}
          <h1 style={{
            fontFamily: 'Syne, sans-serif',
            fontSize: 'clamp(44px, 5.4vw, 76px)',
            fontWeight: 800, lineHeight: 1.15,
            letterSpacing: '-0.04em', marginBottom: 26,
            opacity: visible ? 1 : 0,
            transform: visible ? 'translateY(0)' : 'translateY(20px)',
            transition: 'opacity 0.75s ease 0.2s, transform 0.75s ease 0.2s',
          }}>
            We build the{' '}
            <span style={{
              color: 'transparent',
              backgroundImage: T.gradTxt,
              WebkitBackgroundClip: 'text',
              WebkitTextFillColor: 'transparent',
              backgroundClip: 'text',
              filter: isDark ? 'drop-shadow(0 0 12px rgba(0, 217, 160, 0.4))' : 'drop-shadow(0 0 8px rgba(0, 122, 90, 0.2))',
            }}>
              AI systems
            </span>{' '}
            that run your{' '}
            <span key={wordIdx} style={{
              display: 'inline-block',
              animation: 'hero-word-in 0.5s cubic-bezier(0.16,1,0.3,1)',
              color: T.h1Txt,
            }}>
              {H_WORDS[wordIdx]}
            </span>
          </h1>

          {/* Sub */}
          <p style={{
            fontFamily: 'Inter, sans-serif', fontSize: 17,
            color: T.subTxt, lineHeight: 1.75, maxWidth: 490, marginBottom: 38,
            opacity: visible ? 1 : 0, transform: visible ? 'translateY(0)' : 'translateY(12px)',
            transition: 'opacity 0.65s ease 0.75s, transform 0.65s ease 0.75s, color 0.45s ease',
          }}>
            Custom AI agents, integrations, and automation for med spas, law firms, real estate teams, and B2B operators.{' '}
            <strong style={{ color: T.subStrong, fontWeight: 600, transition: 'color 0.45s ease' }}>
              Production-grade, not prototype.
            </strong>
          </p>

          {/* CTAs */}
          <div style={{
            display: 'flex', gap: 14, flexWrap: 'wrap',
            opacity: visible ? 1 : 0, transform: visible ? 'translateY(0)' : 'translateY(10px)',
            transition: 'opacity 0.5s ease 0.9s, transform 0.5s ease 0.9s',
          }}>
            <a href="https://cal.com/ratan-kumar/ai-automation-startegy-call-with-ratan-quantaeight"
              target="_blank" rel="noopener"
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '14px 28px', background: '#00D9A0',
                color: '#0A0B0E', fontWeight: 700, fontSize: 15,
                fontFamily: 'Inter, sans-serif', borderRadius: 9,
                textDecoration: 'none', transition: 'all 0.22s ease',
                boxShadow: isDark ? '0 4px 20px rgba(0,217,160,0.3)' : '0 4px 16px rgba(0,150,100,0.25)',
              }}
              onMouseMove={e => {
                const rect = e.currentTarget.getBoundingClientRect();
                const x = e.clientX - rect.left - rect.width / 2;
                const y = e.clientY - rect.top - rect.height / 2;
                e.currentTarget.style.transform = `translate(${x * 0.15}px, ${y * 0.15}px)`;
              }}
              onMouseEnter={e => {
                e.currentTarget.style.background = '#00F0B4';
                e.currentTarget.style.boxShadow = isDark
                  ? '0 12px 36px rgba(0,217,160,0.44)'
                  : '0 12px 28px rgba(0,150,100,0.35)';
              }}
              onMouseLeave={e => {
                e.currentTarget.style.background = '#00D9A0';
                e.currentTarget.style.transform = 'translate(0px, 0px)';
                e.currentTarget.style.boxShadow = isDark
                  ? '0 4px 20px rgba(0,217,160,0.3)'
                  : '0 4px 16px rgba(0,150,100,0.25)';
              }}
            >Book a discovery call →</a>

            <a href="#work"
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '14px 28px',
                background: T.ctaGhostBg, color: T.ctaGhostTxt,
                fontWeight: 500, fontSize: 15, fontFamily: 'Inter, sans-serif',
                borderRadius: 9, textDecoration: 'none',
                border: `1px solid ${T.ctaGhostBdr}`,
                transition: 'all 0.22s ease',
              }}
              onMouseEnter={e => {
                e.currentTarget.style.background  = T.ctaGhostHover;
                e.currentTarget.style.borderColor = T.ctaBdrHover;
                e.currentTarget.style.color       = T.h1Txt;
              }}
              onMouseLeave={e => {
                e.currentTarget.style.background  = T.ctaGhostBg;
                e.currentTarget.style.borderColor = T.ctaGhostBdr;
                e.currentTarget.style.color       = T.ctaGhostTxt;
              }}
            >See our work →</a>
          </div>

          {/* Stats strip */}
          <div style={{
            marginTop: 48, display: 'flex', alignItems: 'center', gap: 28,
            flexWrap: 'wrap',
            opacity: visible ? 1 : 0, transition: 'opacity 0.6s ease 1.06s',
          }}>
            {[
              { val: '$1.2M',  sub: 'saved in 6 months',     c: T.statMint   },
              { val: '6 wks',  sub: 'discovery to deployed', c: T.statViolet },
              { val: '99.97%', sub: 'production uptime',     c: T.statAmber  },
            ].map((s, i) => (
              <React.Fragment key={i}>
                <div>
                  <div style={{
                    fontFamily: 'Syne, sans-serif', fontSize: 23, fontWeight: 700,
                    color: s.c, lineHeight: 1, letterSpacing: '-0.02em',
                    transition: 'color 0.45s ease',
                  }}>{s.val}</div>
                  <div style={{
                    fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
                    color: T.statLbl, marginTop: 5, transition: 'color 0.45s ease',
                  }}>{s.sub}</div>
                </div>
                {i < 2 && (
                  <div style={{
                    width: 1, height: 34,
                    background: T.statDivBg, flexShrink: 0,
                    transition: 'background 0.45s ease',
                  }} />
                )}
              </React.Fragment>
            ))}
          </div>
        </div>

        {/* ── RIGHT: live activity card ──────────────────────────────── */}
        <div style={{
          display: 'flex', justifyContent: 'flex-end', alignItems: 'center',
          opacity: visible ? 1 : 0, transform: visible ? 'translateX(0)' : 'translateX(30px)',
          transition: 'opacity 0.85s ease 0.95s, transform 0.85s ease 0.95s',
        }}>
          <div style={{
            width: '100%', maxWidth: 400,
            background: T.cardBg,
            backdropFilter: 'blur(28px) saturate(180%)',
            WebkitBackdropFilter: 'blur(28px) saturate(180%)',
            border: `1px solid ${T.cardBdr}`,
            borderRadius: 18, overflow: 'hidden',
            boxShadow: T.cardShadow,
            animation: 'hero-float 7s ease-in-out infinite',
            transition: 'background 0.45s ease, border-color 0.45s ease, box-shadow 0.45s ease',
          }}>
            {/* Card header */}
            <div style={{
              padding: '13px 18px',
              borderBottom: `1px solid ${T.cardHdrBdr}`,
              background: T.cardHdrBg,
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              transition: 'background 0.45s ease, border-color 0.45s ease',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ display: 'flex', gap: 5 }}>
                  {['#F87171','#FBBF24','#34D399'].map((c, i) => (
                    <span key={i} style={{ width: 9, height: 9, borderRadius: '50%', background: c, opacity: 0.62 }} />
                  ))}
                </div>
                <span style={{
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
                  color: T.cardMonoTxt, letterSpacing: '0.08em',
                  transition: 'color 0.45s ease',
                }}>// AI SYSTEM · LIVE</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                <span style={{
                  width: 5, height: 5, borderRadius: '50%',
                  background: '#00D9A0', boxShadow: '0 0 6px #00D9A0',
                  animation: 'hero-blink 1.5s infinite',
                }} />
                <span style={{
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
                  color: '#00D9A0', letterSpacing: '0.06em',
                }}>processing</span>
              </div>
            </div>

            {/* Activity log */}
            <div style={{ padding: '18px 18px 14px' }}>
              <div style={{
                fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
                color: T.cardSecTxt, letterSpacing: '0.1em', marginBottom: 13,
                transition: 'color 0.45s ease',
              }}>ACTIVE WORKFLOW</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
                {act.map((item, i) => {
                  const isVis = i <= logStep;
                  return (
                    <div key={`${actIdx}-${i}`} style={{
                      display: 'flex', gap: 10, alignItems: 'flex-start',
                      opacity: isVis ? 1 : 0.08,
                      transform: isVis ? 'translateX(0)' : 'translateX(-8px)',
                      transition: 'opacity 0.4s ease, transform 0.4s ease',
                    }}>
                      <span style={{
                        fontSize: 11, color: tStyle[item.t], flexShrink: 0,
                        marginTop: 1, width: 12, textAlign: 'center', lineHeight: 1.55,
                        transition: 'color 0.45s ease',
                      }}>{tIcon[item.t]}</span>
                      <span style={{
                        fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
                        color: tStyle[item.t], lineHeight: 1.6,
                        transition: 'color 0.45s ease',
                      }}>{item.m}</span>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Divider */}
            <div style={{
              height: 1, background: T.cardDivider, margin: '0 18px',
              transition: 'background 0.45s ease',
            }} />

            {/* Footer metrics, time-based tasks today */}
            <div style={{ padding: '12px 18px 15px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
              <div>
                <div style={{
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
                  color: T.cardLbl, marginBottom: 4, letterSpacing: '0.08em',
                  transition: 'color 0.45s ease',
                }}>TODAY · AUTOMATED</div>
                <div style={{ display: 'flex', gap: 16, alignItems: 'baseline' }}>
                  <div>
                    <span style={{
                      fontFamily: 'Syne, sans-serif', fontSize: 16, fontWeight: 700,
                      color: T.statMint, transition: 'color 0.45s ease',
                    }}>{tasksToday}</span>
                    <span style={{
                      fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
                      color: T.cardMonoTxt, marginLeft: 4, transition: 'color 0.45s ease',
                    }}>tasks</span>
                  </div>
                  <div>
                    <span style={{
                      fontFamily: 'Syne, sans-serif', fontSize: 16, fontWeight: 700,
                      color: T.statAmber, transition: 'color 0.45s ease',
                    }}>0</span>
                    <span style={{
                      fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
                      color: T.cardMonoTxt, marginLeft: 4, transition: 'color 0.45s ease',
                    }}>human</span>
                  </div>
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
                  color: T.cardLbl, marginBottom: 4, letterSpacing: '0.08em',
                  transition: 'color 0.45s ease',
                }}>UPTIME</div>
                <div style={{
                  fontFamily: 'Syne, sans-serif', fontSize: 16, fontWeight: 700,
                  color: T.statViolet, transition: 'color 0.45s ease',
                }}>99.97%</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ── Bottom industry ticker ─────────────────────────────────────────── */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        borderTop: `1px solid ${T.tickerBdr}`,
        overflow: 'hidden', padding: '13px 0',
        background: T.tickerBg,
        backdropFilter: 'blur(8px)',
        transition: 'background 0.45s ease, border-color 0.45s ease',
      }}>
        <div style={{
          display: 'flex', animation: 'hero-ticker 32s linear infinite',
          whiteSpace: 'nowrap', width: 'max-content',
        }}>
          {[...Array(4)].map((_, rep) =>
            ['Production AI','Code You Own','Fixed Price','No Lock-in','Spec Locked Before Code',
             'Loom Demo Every Friday','6-Week Delivery','Multi-agent Systems','99.97% Uptime SLA',
             'Real Users in Week 3','Full Source Handoff'].map((v, i) => (
              <span key={`${rep}-${i}`} style={{
                fontFamily: 'JetBrains Mono, monospace', fontSize: 12,
                color: T.tickerTxt, letterSpacing: '0.08em', padding: '0 22px',
                transition: 'color 0.45s ease',
              }}>
                {v}
                <span style={{
                  marginLeft: 18, color: T.tickerDot,
                  opacity: T.tickerDotOp, transition: 'color 0.45s ease',
                }}>+</span>
              </span>
            ))
          )}
        </div>
      </div>

      <style>{`
        @keyframes hero-blink  { 0%,100%{opacity:1} 50%{opacity:0.3} }
        @keyframes hero-ticker { from{transform:translateX(0)} to{transform:translateX(-25%)} }
        @keyframes hero-float  { 0%,100%{transform:translateY(0px)} 50%{transform:translateY(-9px)} }
        @keyframes hero-word-in {
          from { opacity: 0; transform: translateY(14px); filter: blur(4px); }
          to   { opacity: 1; transform: translateY(0);    filter: blur(0); }
        }
        @media (max-width: 1020px) { .hero-grid { grid-template-columns: 1fr !important; gap: 48px !important; } }
        @media (max-width: 640px)  { .hero-grid { padding: 0 24px !important; } }
      `}</style>
    </section>
  );
}

Object.assign(window, { Hero });
