// Data Mirai — Landing page
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ─── Scroll Reveal ──────────────────────────────────────────────────────────
function useReveal(deps) {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal:not(.in)');
    if (!els.length) return;
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add('in');
          observer.unobserve(entry.target);
        }
      });
    }, { threshold: 0.1, rootMargin: '0px 0px -60px 0px' });
    els.forEach((el) => observer.observe(el));
    return () => observer.disconnect();
  }, deps);
}

// ─── Typed Pitch ────────────────────────────────────────────────────────────
function TypedPitch({ pre, strong, post, end }) {
  const [typed, setTyped] = useState(0);
  useEffect(() => {
    if (typed < strong.length) {
      const t = setTimeout(() => setTyped(typed + 1), 40 + Math.random() * 30);
      return () => clearTimeout(t);
    }
  }, [typed, strong]);
  const done = typed >= strong.length;
  return (
    <p className="hero-pitch">
      {pre}{' '}
      <b style={{
        background: 'linear-gradient(135deg, var(--grad-orange), var(--grad-purple))',
        WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent',
      }}>
        {strong.slice(0, typed)}{!done && <span className="caret" style={{color: 'var(--accent)'}}></span>}
      </b>
      {post}<b>{end}</b>
    </p>
  );
}

// ─── Hero Orbit ─────────────────────────────────────────────────────────────
function OrbitChip({ x, y, kind, children, big, small, agent }) {
  const left = (x / 560) * 100;
  const top = (y / 560) * 100;
  const palette = {
    core:    { c: '#fff', bg: 'linear-gradient(135deg, rgba(234,88,12,0.25), rgba(147,51,234,0.35))', border: 'rgba(255,255,255,0.18)' },
    trigger: { c: 'var(--c-trigger)', bg: 'rgba(22,163,74,0.12)', border: 'rgba(22,163,74,0.35)' },
    logic:   { c: 'var(--c-logic)',   bg: 'rgba(37,99,235,0.12)',  border: 'rgba(37,99,235,0.35)' },
    ai:      { c: 'var(--c-ai)',      bg: 'rgba(147,51,234,0.12)', border: 'rgba(147,51,234,0.35)' },
    data:    { c: 'var(--c-data)',    bg: 'rgba(234,88,12,0.12)',  border: 'rgba(234,88,12,0.35)' },
    agent:   { c: 'var(--c-agent)',   bg: 'rgba(245,158,11,0.12)', border: 'rgba(245,158,11,0.35)' },
    output:  { c: 'var(--c-output)',  bg: 'rgba(236,72,153,0.12)', border: 'rgba(236,72,153,0.35)' },
  };
  const p = palette[kind] || palette.core;
  const style = {
    position: 'absolute',
    left: `${left}%`,
    top: `${top}%`,
    transform: 'translate(-50%, -50%)',
    background: p.bg,
    color: p.c,
    border: `1px solid ${p.border}`,
    backdropFilter: 'blur(14px)',
    borderRadius: big ? '14px' : '10px',
    padding: big ? '14px 18px' : (small ? '5px 9px' : '7px 11px'),
    fontFamily: 'var(--font-mono)',
    fontSize: big ? '12px' : (small ? '10px' : '11px'),
    letterSpacing: '0.04em',
    whiteSpace: 'nowrap',
    boxShadow: big
      ? '0 20px 60px -20px rgba(147, 51, 234, 0.6), 0 0 0 4px rgba(167,139,250,0.05)'
      : `0 0 20px ${p.c}33, 0 0 0 1px ${p.border}`,
    zIndex: big ? 5 : (agent ? 4 : 3),
    minWidth: big ? '120px' : 'auto',
    textAlign: big ? 'center' : 'left',
    lineHeight: big ? '1.2' : '1.3',
  };
  return (
    <div style={style}>
      {kind !== 'core' && (
        <span style={{
          display: 'inline-block',
          width: 6, height: 6, borderRadius: '50%',
          background: p.c, boxShadow: `0 0 8px ${p.c}`,
          marginRight: 6, verticalAlign: 'middle',
        }} />
      )}
      <span style={{ color: kind === 'core' ? '#fff' : 'var(--fg)' }}>{children}</span>
    </div>
  );
}

function HeroOrbit({ t }) {
  const wrapRef = useRef(null);
  const [time, setTime] = useState(0);

  useEffect(() => {
    let raf, start = performance.now();
    const loop = (now) => { setTime((now - start) / 1000); raf = requestAnimationFrame(loop); };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  const S = 560, cx = S / 2, cy = S / 2;
  const agentR = 140, planetR = 215;

  // Deterministic star field (like tucania-engine)
  const stars = useMemo(() => Array.from({ length: 110 }, (_, i) => ({
    x: (i * 137.5 + 23) % S, y: (i * 89.7 + 17) % S,
    r: 0.3 + (i % 5) * 0.25, op: 0.08 + (i % 7) * 0.05,
  })), []);

  const COLORS = { agent: '#f59e0b', output: '#ec4899', logic: '#2563eb', ai: '#9333ea', data: '#ea580c', trigger: '#16a34a' };

  const agentDefs = [
    { name: t.orbit.n1, kind: 'agent',  color: COLORS.agent },
    { name: t.orbit.n2, kind: 'output', color: COLORS.output },
    { name: t.orbit.n3, kind: 'logic',  color: COLORS.logic },
    { name: t.orbit.n4, kind: 'ai',     color: COLORS.ai },
  ];
  const planetDefs = [
    { name: t.orbit.p1, kind: 'data',    color: COLORS.data },
    { name: t.orbit.p2, kind: 'trigger', color: COLORS.trigger },
    { name: t.orbit.p3, kind: 'data',    color: COLORS.data },
    { name: t.orbit.p4, kind: 'output',  color: COLORS.output },
  ];

  const agents = agentDefs.map((a, i) => {
    const angle = (Math.PI * 2 * i) / 4 + Math.PI * 0.25 + time * 0.06;
    return { ...a, x: cx + Math.cos(angle) * agentR, y: cy + Math.sin(angle) * agentR };
  });
  const planets = planetDefs.map((p, i) => {
    const angle = (Math.PI * 2 * i) / 4 + time * 0.035;
    return { ...p, x: cx + Math.cos(angle) * planetR, y: cy + Math.sin(angle) * planetR };
  });

  return (
    <div className="orbit-stage" ref={wrapRef}>
      {/* Nebula glow */}
      <div className="orbit-nebula" />

      <svg viewBox={`0 0 ${S} ${S}`} width="100%" height="100%" style={{position:'absolute', inset:0}}>
        <defs>
          <radialGradient id="coreGrad">
            <stop offset="0%" stopColor="#ea580c" stopOpacity="0.9" />
            <stop offset="50%" stopColor="#9333ea" stopOpacity="0.4" />
            <stop offset="100%" stopColor="#9333ea" stopOpacity="0" />
          </radialGradient>
          <filter id="glowS"><feGaussianBlur stdDeviation="6" /></filter>
          <filter id="glowL"><feGaussianBlur stdDeviation="14" /></filter>
        </defs>

        {/* Star field */}
        {stars.map((s, i) => <circle key={i} cx={s.x} cy={s.y} r={s.r} fill="white" opacity={s.op} />)}
        {/* Twinkling stars */}
        {[0, 15, 33, 52, 71, 88].map((idx) => {
          const s = stars[idx];
          return <circle key={`tw${idx}`} cx={s.x} cy={s.y} r={s.r + 0.5} fill="white"
            opacity={0.3 + Math.sin(time * 1.5 + idx) * 0.3} />;
        })}

        {/* Orbit rings */}
        <circle cx={cx} cy={cy} r={agentR} fill="none" stroke="rgba(167,139,250,0.1)" strokeWidth="1" strokeDasharray="3 9" />
        <circle cx={cx} cy={cy} r={planetR} fill="none" stroke="rgba(6,182,212,0.07)" strokeWidth="1" strokeDasharray="2 8" />

        {/* Agent ↔ center dashed lines */}
        {agents.map((a, i) => (
          <line key={`cl${i}`} x1={cx} y1={cy} x2={a.x} y2={a.y}
            stroke={a.color} strokeOpacity="0.12" strokeWidth="0.8" strokeDasharray="2 5" />
        ))}

        {/* Agent ↔ planet bezier curves */}
        {agents.map((a, ai) => {
          const p = planets[ai % planets.length];
          const mx = (a.x + p.x) / 2 + (cx - (a.x + p.x) / 2) * 0.4;
          const my = (a.y + p.y) / 2 + (cy - (a.y + p.y) / 2) * 0.4;
          return <path key={`bz${ai}`} d={`M${a.x},${a.y} Q${mx},${my} ${p.x},${p.y}`}
            fill="none" stroke={a.color} strokeWidth="0.5" opacity="0.06" />;
        })}

        {/* Traveling pulses — agent to center */}
        {agents.map((a, i) => {
          const f = ((time * 0.45) + i * 0.25) % 1;
          const px = cx + (a.x - cx) * f, py = cy + (a.y - cy) * f;
          return (<g key={`tp${i}`}>
            <circle cx={px} cy={py} r={5} fill={a.color} opacity="0.12" filter="url(#glowS)" />
            <circle cx={px} cy={py} r={2} fill={a.color} opacity="0.8" />
          </g>);
        })}

        {/* Traveling dots — agent to planet bezier */}
        {agents.map((a, ai) => {
          const p = planets[ai % planets.length];
          const f = ((time * 0.3) + ai * 0.4) % 1;
          const mx = (a.x + p.x) / 2 + (cx - (a.x + p.x) / 2) * 0.4;
          const my = (a.y + p.y) / 2 + (cy - (a.y + p.y) / 2) * 0.4;
          const t1 = 1 - f;
          const bx = t1*t1*a.x + 2*t1*f*mx + f*f*p.x;
          const by = t1*t1*a.y + 2*t1*f*my + f*f*p.y;
          return <circle key={`bd${ai}`} cx={bx} cy={by} r={1.5} fill={a.color} opacity="0.45" />;
        })}

        {/* Core — glow + body + pulse ring */}
        <circle cx={cx} cy={cy} r={55} fill="url(#coreGrad)" opacity="0.35" filter="url(#glowL)" />
        <circle cx={cx} cy={cy} r={38} fill="rgba(147,51,234,0.08)" stroke="rgba(167,139,250,0.35)" strokeWidth="1.5" />
        {(() => {
          const pr = 48 + Math.sin(time * 1.6) * 10;
          const po = 0.15 * Math.max(0, Math.cos(time * 1.6));
          return <circle cx={cx} cy={cy} r={pr} fill="none" stroke="rgba(167,139,250,0.3)" strokeWidth="1" strokeDasharray="3 3" opacity={po} />;
        })()}

        {/* Agent glow halos + pulse rings */}
        {agents.map((a, i) => {
          const pr = 20 + Math.sin(time * 2.5 + i * 1.5) * 9;
          const po = 0.35 * Math.max(0, Math.cos(time * 2.5 + i * 1.5));
          return (<g key={`ah${i}`}>
            <circle cx={a.x} cy={a.y} r={24} fill={a.color} opacity="0.07" filter="url(#glowS)" />
            <circle cx={a.x} cy={a.y} r={pr} fill="none" stroke={a.color} strokeWidth="1" opacity={po} />
          </g>);
        })}

        {/* Planet glow halos */}
        {planets.map((p, i) => (
          <circle key={`ph${i}`} cx={p.x} cy={p.y} r={16} fill={p.color} opacity="0.06" filter="url(#glowS)" />
        ))}
      </svg>

      {/* HTML glass chips */}
      <OrbitChip x={cx} y={cy} kind="core" big>
        <div>{t.orbit.core.split('\n').map((s,i) => <div key={i}>{s}</div>)}</div>
      </OrbitChip>
      {agents.map((a) => <OrbitChip key={a.name} x={a.x} y={a.y} kind={a.kind} agent>{a.name}</OrbitChip>)}
      {planets.map((p) => <OrbitChip key={p.name} x={p.x} y={p.y} kind={p.kind} small>{p.name}</OrbitChip>)}
    </div>
  );
}

// ─── Graph Demo ─────────────────────────────────────────────────────────────
function kindColor(k) {
  return {
    trigger: '#16a34a', logic: '#2563eb', ai: '#9333ea',
    data: '#ea580c', agent: '#f59e0b', output: '#ec4899',
  }[k] || '#a78bfa';
}

function getLogMessage(node) {
  const msgs = {
    trigger: 'lead received · acme.co · n=1',
    data: 'enriched 1 contact · 42 fields · 230ms',
    logic: 'icp_score=83 · qualified=true',
    ai: 'generated email · 142 tokens · $0.0008',
    agent: 'astronaut Sales picked up · tools loaded',
    output: 'draft → gmail · scheduled 09:30 PT',
  };
  return msgs[node.k] || 'tick';
}

function GraphDemo({ t }) {
  const [running, setRunning] = useState(true);
  const [activeIdx, setActiveIdx] = useState(0);
  const [logs, setLogs] = useState([]);
  const timerRef = useRef(null);
  const nodes = t.demo.nodes;

  const positions = [
    { x: 30,  y: 60  },
    { x: 200, y: 30  },
    { x: 200, y: 200 },
    { x: 380, y: 60  },
    { x: 380, y: 230 },
    { x: 560, y: 150 },
  ];

  const edges = [
    [0, 1], [0, 2], [1, 3], [2, 4], [3, 5], [4, 5],
  ];

  useEffect(() => {
    if (!running) return;
    timerRef.current = setInterval(() => {
      setActiveIdx((i) => {
        const next = (i + 1) % nodes.length;
        const now = new Date();
        const ts = `${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}:${String(now.getSeconds()).padStart(2,'0')}`;
        setLogs((prev) => {
          const node = nodes[next];
          const newLog = { t: ts, tag: `[${node.k}]`, msg: getLogMessage(node) };
          return [newLog, ...prev].slice(0, 18);
        });
        return next;
      });
    }, 1200);
    return () => clearInterval(timerRef.current);
  }, [running, nodes]);

  useEffect(() => {
    const now = new Date();
    const ts = `${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}:${String(now.getSeconds()).padStart(2,'0')}`;
    setLogs([
      { t: ts, tag: '[boot]', msg: 'engine v0.42.0 booted · 6 nodes · MIT', ok: true },
      { t: ts, tag: '[wsk]', msg: 'subscribed to @webhook/leads', ok: true },
    ]);
  }, []);

  const step = () => {
    setActiveIdx((i) => (i + 1) % nodes.length);
  };

  return (
    <div className="demo-shell">
      <div className="demo-topbar">
        <div className="traffic"><span></span><span></span><span></span></div>
        <div className="crumb">datamirai.app — <b style={{color:'var(--fg)'}}>{t.demo.crumb}</b></div>
        <div className="ctrls">
          <button className={`pill ${running ? 'live' : ''}`}>
            <span style={{
              display: 'inline-block', width: 6, height: 6, borderRadius: '50%',
              background: running ? 'var(--c-trigger)' : 'var(--fg-3)',
              marginRight: 6,
              boxShadow: running ? '0 0 6px var(--c-trigger)' : 'none',
            }}></span>
            {running ? t.demo.live : t.demo.paused}
          </button>
          <button className="pill active" onClick={() => setRunning((r) => !r)}>
            {running ? t.demo.pause : t.demo.run}
          </button>
          <button className="pill" onClick={step}>{t.demo.step}</button>
        </div>
      </div>

      <div className="demo-body">
        <div className="demo-side">
          <h4>{t.demo.panels.nodes}</h4>
          <div className="node-list">
            {['trigger','logic','ai','data','agent','output'].map((k) => (
              <div key={k} className="node-item" data-kind={k}>
                <span className="swatch"></span>
                <span style={{textTransform:'capitalize'}}>{k}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="demo-canvas">
          <svg viewBox="0 0 680 320" width="100%" height="100%" preserveAspectRatio="xMidYMid meet" style={{position:'absolute', inset:0}}>
            {edges.map(([a, b], i) => {
              const pa = positions[a];
              const pb = positions[b];
              const x1 = pa.x + 70, y1 = pa.y + 24;
              const x2 = pb.x,      y2 = pb.y + 24;
              const mx = (x1 + x2) / 2;
              const path = `M ${x1} ${y1} C ${mx} ${y1}, ${mx} ${y2}, ${x2} ${y2}`;
              const isActive = activeIdx === b && running;
              return (
                <g key={i}>
                  <path d={path} fill="none"
                    stroke="var(--fg-3)" strokeOpacity={0.3} strokeWidth={1.2}
                  />
                  {isActive && (
                    <path d={path} fill="none"
                      stroke={kindColor(nodes[b].k)} strokeWidth={2}
                      strokeDasharray="6 6"
                      style={{ animation: 'dash 0.8s linear infinite' }}
                    />
                  )}
                </g>
              );
            })}
          </svg>
          <style>{`@keyframes dash { to { stroke-dashoffset: -24; } }`}</style>

          {nodes.map((n, i) => {
            const p = positions[i];
            const active = activeIdx === i;
            return (
              <div key={i}
                className={`flow-node ${active ? 'active' : ''}`}
                data-kind={n.k}
                style={{
                  left: `${(p.x / 680) * 100}%`,
                  top: p.y,
                  width: 140,
                }}>
                <div className="nh">
                  <span className="led"></span>
                  <span>{n.k}</span>
                </div>
                <div className="nl">{n.l}</div>
                <div className="nm">{n.m}</div>
              </div>
            );
          })}
        </div>

        <div className="demo-right">
          <div>
            <h4>{t.demo.panels.kpis}</h4>
            <div className="kpi-grid">
              {t.demo.kpi.map((k, i) => (
                <div key={i} className="kpi">
                  <div className="v">{k.v}</div>
                  <div className="k">{k.k}</div>
                </div>
              ))}
            </div>
          </div>
          <div style={{flex: 1, display: 'flex', flexDirection: 'column'}}>
            <h4>{t.demo.panels.logs}</h4>
            <div className="log">
              {logs.map((l, i) => (
                <div key={i} className="log-line" style={{opacity: 1 - i * 0.05}}>
                  <span className="t">{l.t}</span>
                  <span className={`tag ${l.ok ? 'ok' : ''}`}>{l.tag}</span>
                  <span style={{color: l.ok ? 'var(--c-trigger)' : 'var(--fg-2)'}}>{l.msg}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Shift Arrow ────────────────────────────────────────────────────────────
function ShiftArrow({ label }) {
  return (
    <div style={{
      width: '100%', height: '100%', display: 'flex',
      flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8,
    }}>
      <svg width="40" height="60" viewBox="0 0 40 60" fill="none">
        <defs>
          <linearGradient id="shiftG" x1="0" y1="0" x2="0" y2="60">
            <stop offset="0" stopColor="var(--c-data)" />
            <stop offset="1" stopColor="var(--c-ai)" />
          </linearGradient>
        </defs>
        <path d="M20 5 L20 50 M10 40 L20 50 L30 40" stroke="url(#shiftG)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
      <span style={{
        fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em',
        color: 'var(--fg-3)', writingMode: 'horizontal-tb',
      }}>{label}</span>
    </div>
  );
}

// ─── Step Illustrations ─────────────────────────────────────────────────────
function StepIllu({ n }) {
  if (n === 0) {
    return (
      <svg viewBox="0 0 280 80" width="100%" height="80">
        <g fontFamily="var(--font-mono)" fontSize="9" fill="var(--fg-3)">
          {[
            { x: 12, y: 18, w: 70, h: 36, c: 'var(--c-trigger)', l: 'trigger' },
            { x: 100, y: 14, w: 70, h: 32, c: 'var(--c-logic)', l: 'logic' },
            { x: 100, y: 50, w: 70, h: 22, c: 'var(--c-data)', l: 'data' },
            { x: 190, y: 30, w: 78, h: 32, c: 'var(--c-output)', l: 'output' },
          ].map((b, i) => (
            <g key={i}>
              <rect x={b.x} y={b.y} width={b.w} height={b.h} rx="6"
                fill="none" stroke={b.c} strokeWidth="1" opacity="0.7" />
              <circle cx={b.x + 6} cy={b.y + 10} r="2" fill={b.c} />
              <text x={b.x + 12} y={b.y + 13} fill={b.c}>{b.l}</text>
            </g>
          ))}
          <path d="M 82 36 C 95 36, 95 30, 100 30 M 82 36 C 95 36, 95 61, 100 61 M 170 30 C 180 30, 180 46, 190 46 M 170 61 C 180 61, 180 46, 190 46"
            stroke="var(--fg-4)" strokeOpacity="0.5" fill="none" strokeDasharray="2 3" />
        </g>
      </svg>
    );
  }
  if (n === 1) {
    return (
      <svg viewBox="0 0 280 80" width="100%" height="80">
        <g fontFamily="var(--font-mono)" fontSize="9" fill="var(--fg-3)">
          <circle cx="140" cy="40" r="10" fill="var(--c-trigger)" opacity="0.3" />
          <circle cx="140" cy="40" r="6" fill="var(--c-trigger)" />
          <text x="140" y="62" textAnchor="middle" fill="var(--c-trigger)">agent</text>
          {[
            { x: 60, y: 24, l: 'CRM', c: 'var(--c-data)' },
            { x: 60, y: 60, l: 'PG', c: 'var(--c-logic)' },
            { x: 220, y: 24, l: 'API', c: 'var(--c-output)' },
            { x: 220, y: 60, l: 'S3', c: 'var(--c-agent)' },
          ].map((p, i) => (
            <g key={i}>
              <line x1="140" y1="40" x2={p.x} y2={p.y} stroke={p.c} strokeOpacity="0.35" strokeDasharray="2 3" />
              <circle cx={p.x} cy={p.y} r="6" fill={p.c} opacity="0.85" />
              <text x={p.x} y={p.y - 10} textAnchor="middle" fill={p.c}>{p.l}</text>
            </g>
          ))}
        </g>
      </svg>
    );
  }
  return (
    <svg viewBox="0 0 280 80" width="100%" height="80">
      <g fontFamily="var(--font-mono)" fontSize="9" fill="var(--fg-3)">
        {[18, 28, 14, 36, 22, 40, 30, 48, 34, 52, 42, 60].map((h, i) => (
          <rect key={i} x={10 + i * 18} y={70 - h} width="10" height={h}
            fill="var(--c-trigger)" opacity={0.4 + i * 0.04} rx="2" />
        ))}
        <text x="10" y="12" fill="var(--c-trigger)">runs / hr ↑</text>
        <text x="270" y="12" textAnchor="end" fill="var(--fg-3)">+34%</text>
      </g>
    </svg>
  );
}

// ─── Particles ──────────────────────────────────────────────────────────────
function Particles({ count }) {
  const particles = useMemo(() => {
    return Array.from({ length: count }, () => ({
      left: Math.random() * 100,
      top: 60 + Math.random() * 40,
      delay: Math.random() * 12,
      duration: 8 + Math.random() * 10,
      size: 1 + Math.random() * 2,
    }));
  }, [count]);
  return (
    <div className="particles" style={{position:'fixed', inset:0, zIndex:0, pointerEvents:'none'}}>
      {particles.map((p, i) => (
        <span key={i} className="particle" style={{
          left: `${p.left}%`,
          top: `${p.top}%`,
          width: p.size, height: p.size,
          animationDelay: `${p.delay}s`,
          animationDuration: `${p.duration}s`,
          background: 'var(--accent-2)',
        }} />
      ))}
    </div>
  );
}

// ─── NavBar ─────────────────────────────────────────────────────────────────
function NavBar({ t, lang, theme, toggleLang, toggleTheme }) {
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);

  return (
    <>
      {/* Desktop nav — floating glass bar */}
      <nav className="nav">
        <div className="nav-left">
          <div className="nav-links">
            <a href="#problema">{t.nav.product}</a>
            <a href="#como">{t.nav.how}</a>
            <a href="#paths">{t.nav.paths}</a>
          </div>
        </div>
        <a href="#" className="nav-brand" onClick={(e) => e.preventDefault()}>
          <span className="nav-logo">未来</span>
          <span className="nav-wordmark">Data Mirai</span>
        </a>
        <div className="nav-right">
          <button className="nav-ghost" onClick={toggleLang}>{lang === 'es' ? 'EN' : 'ES'}</button>
          <button className="nav-ghost" onClick={toggleTheme} aria-label="Toggle theme">
            {theme === 'dark' ? (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
            ) : (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
            )}
          </button>
          <a href="#waitlist" className="nav-cta">{t.nav.cta}</a>
        </div>
      </nav>

      {/* Mobile trigger — floating pill top-left */}
      <button className={`mob-trigger ${menuOpen ? 'mob-trigger--open' : ''}`} onClick={() => setMenuOpen(!menuOpen)}>
        <span className="mob-trigger-logo">未来</span>
        <span className="mob-trigger-label">Data Mirai</span>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
          style={{ transition: 'transform 0.3s ease', transform: menuOpen ? 'rotate(180deg)' : 'rotate(0deg)' }}>
          <polyline points="6 9 12 15 18 9" />
        </svg>
      </button>

      {/* Mobile fullscreen overlay */}
      <div className={`mob-overlay ${menuOpen ? 'mob-overlay--open' : ''}`}>
        <div className="mob-overlay-content">
          <div className="mob-overlay-brand">
            <span className="mob-overlay-kanji">未来</span>
            <span className="mob-overlay-name">Data Mirai</span>
          </div>

          <div className="mob-overlay-links">
            <a href="#problema" onClick={() => setMenuOpen(false)}>{t.nav.product}</a>
            <a href="#como" onClick={() => setMenuOpen(false)}>{t.nav.how}</a>
            <a href="#paths" onClick={() => setMenuOpen(false)}>{t.nav.paths}</a>
          </div>

          <div className="mob-overlay-actions">
            <button className="mob-overlay-ghost" onClick={() => { toggleLang(); }}>{lang === 'es' ? 'English' : 'Español'}</button>
            <button className="mob-overlay-ghost" onClick={() => { toggleTheme(); }}>
              {theme === 'dark' ? (
                <><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{verticalAlign:'-2px'}}><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg> Light</>
              ) : (
                <><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{verticalAlign:'-2px'}}><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg> Dark</>
              )}
            </button>
          </div>

          <a href="#waitlist" className="mob-overlay-cta" onClick={() => setMenuOpen(false)}>{t.nav.cta}</a>
        </div>
      </div>
    </>
  );
}

// ─── Catalog ────────────────────────────────────────────────────────────────
function Catalog({ t }) {
  const [active, setActive] = useState('all');
  const items = t.catalog.items;
  const visible = active === 'all' ? items : items.filter((it) => it.cat === active);

  return (
    <section id="catalog">
      <div className="reveal">
        <div className="section-tag" data-color="green"><span className="dot"></span>{t.catalog.tag}</div>
        <h2 className="section-title">{t.catalog.title}</h2>
        <p className="section-lede">{t.catalog.lede}</p>
      </div>
      <div className="catalog-filters">
        {t.catalog.filters.map((f) => (
          <button
            key={f.id}
            className={`cf-pill ${active === f.id ? 'active' : ''}`}
            onClick={() => setActive(f.id)}>
            {f.name}<span className="cf-count">{f.count}</span>
          </button>
        ))}
      </div>
      <div className="catalog-grid">
        {visible.map((it, i) => (
          <div key={`${active}-${i}`} className="catalog-card" data-k={it.kind}>
            <div className="catalog-dept"><span className="dot"></span>{it.dept}</div>
            <div className="catalog-title">{it.t}</div>
            <div className="catalog-p">{it.p}</div>
            <div className="catalog-foot">
              <span className="catalog-freq">{it.freq}</span>
              <span className="catalog-saves">{t.catalog.saves_label} <b>{it.saves}</b></span>
            </div>
          </div>
        ))}
      </div>
      <div className="catalog-more">{t.catalog.cta_more}</div>
    </section>
  );
}

// ─── Waitlist ───────────────────────────────────────────────────────────────
const WAITLIST_URL = 'https://script.google.com/macros/s/AKfycbx5PcBDn5FW1ABt4HKMl0HTdMjUKsQP1TA4Z2JHnB6aNYRcKg3fm4VKb-wGlYFjdRCk/exec';

function useSessionData() {
  const start = useRef(Date.now());
  const maxScroll = useRef(0);

  useEffect(() => {
    const onScroll = () => {
      const depth = Math.round((window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100);
      if (depth > maxScroll.current) maxScroll.current = depth;
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return useCallback(() => {
    const params = new URLSearchParams(window.location.search);
    const w = window.innerWidth;
    return {
      referrer: document.referrer || 'direct',
      utm_source: params.get('utm_source') || '',
      utm_medium: params.get('utm_medium') || '',
      utm_campaign: params.get('utm_campaign') || '',
      device: w < 480 ? 'mobile' : w < 1024 ? 'tablet' : 'desktop',
      screen: `${window.screen.width}x${window.screen.height}`,
      browser_lang: navigator.language || '',
      timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || '',
      scroll_depth: maxScroll.current + '%',
      time_on_page: Math.round((Date.now() - start.current) / 1000),
    };
  }, []);
}

function Waitlist({ t, lang }) {
  const [email, setEmail] = useState('');
  const [hp, setHp] = useState('');
  const [status, setStatus] = useState('idle');
  const getSession = useSessionData();

  const submit = (e) => {
    e.preventDefault();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return;
    setStatus('sending');

    const payload = {
      email,
      lang,
      _hp: hp,
      ...getSession(),
    };

    fetch(WAITLIST_URL, {
      method: 'POST',
      body: JSON.stringify(payload),
    })
      .then(() => setStatus('done'))
      .catch(() => setStatus('done'));
  };

  if (status === 'done') {
    return <div className="email-success"><span style={{width:6,height:6,borderRadius:'50%',background:'var(--c-trigger)',boxShadow:'0 0 6px var(--c-trigger)'}}></span>{t.waitlist.success}</div>;
  }
  return (
    <form className="email-form" onSubmit={submit}>
      <input type="email" placeholder={t.waitlist.placeholder} value={email} onChange={(e) => setEmail(e.target.value)} required />
      {/* Honeypot — invisible to humans, bots fill it */}
      <input type="text" value={hp} onChange={(e) => setHp(e.target.value)}
        style={{position:'absolute',left:'-9999px',tabIndex:-1}} autoComplete="off" aria-hidden="true" />
      <button type="submit" className="btn primary" disabled={status === 'sending'}>
        {status === 'sending' ? '...' : t.waitlist.cta}
      </button>
    </form>
  );
}

// ─── App ────────────────────────────────────────────────────────────────────
function App() {
  const [lang, setLang] = useState('es');
  const [theme, setTheme] = useState('dark');
  const [langFade, setLangFade] = useState(false);
  const t = window.I18N[lang];

  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);

  useReveal([lang]);

  const toggleLang = () => {
    setLangFade(true);
    setTimeout(() => {
      setLang(lang === 'es' ? 'en' : 'es');
    }, 50);
    setTimeout(() => setLangFade(false), 360);
  };

  return (
    <div className={`app${langFade ? ' lang-fade' : ''}`}>
      {/* Background */}
      <div className="cosmos"></div>
      <div className="grid-overlay"></div>
      <Particles count={28} />

      {/* NAV — floating glass, logo centered */}
      <NavBar t={t} lang={lang} theme={theme} toggleLang={toggleLang} toggleTheme={() => setTheme(theme === 'dark' ? 'light' : 'dark')} />

      {/* HERO */}
      <section className="hero">
        <div className="hero-left">
          <div className="hero-eyebrow">
            <span className="pulse"></span>
            {t.hero.eyebrow}
          </div>
          <h1 className="hero-title">
            <span className="row"><span className="word data">DATA</span></span>
            <span className="row"><span className="word mirai">MIRAI</span></span>
          </h1>
          <TypedPitch
            pre={t.hero.pitch_pre}
            strong={t.hero.pitch_strong}
            post={t.hero.pitch_post}
            end={t.hero.pitch_end}
          />
          <div className="hero-cta">
            <a href="#waitlist" className="btn primary">{t.hero.cta_primary}</a>
            <a href="#catalog" className="btn">{t.hero.cta_secondary}</a>
          </div>
        </div>
        <div className="hero-right">
          <HeroOrbit t={t} />
        </div>
      </section>

      {/* MIRAI — storytelling */}
      <section className="mirai-section">
        <div className="reveal mirai-inner">
          <div className="mirai-kanji">未来</div>
          <div className="mirai-reading">/ mi·rai /</div>
          <div className="mirai-meaning">{t.mirai.meaning}</div>
          <p className="mirai-story" dangerouslySetInnerHTML={{__html: t.mirai.story}} />
        </div>
      </section>

      {/* PROBLEMA */}
      <section id="problema">
        <div className="reveal">
          <div className="section-tag" data-color="orange"><span className="dot"></span>{t.problema.tag}</div>
          <h2 className="section-title">{t.problema.title}</h2>
          <p className="section-lede">{t.problema.lede}</p>
        </div>
        <div className="problema-grid">
          {t.problema.stats.map((s, i) => (
            <div className="stat-card reveal" key={i} style={{transitionDelay: `${i*80}ms`}}>
              <div className="num">{s.n}<span className="unit">{s.u}</span></div>
              <div className="lbl">{s.l}</div>
              <div className="ex">{s.ex}</div>
            </div>
          ))}
        </div>
      </section>

      {/* SHIFT */}
      <section id="shift" className="shift-section">
        <div className="reveal shift-header">
          <div className="section-tag" data-color="purple"><span className="dot"></span>{t.shift.tag}</div>
          <h2 className="section-title shift-title">{t.shift.title}</h2>
        </div>
        <div className="shift">
          <div className="shift-side before reveal">
            <div className="label"><span className="dot" style={{width:8,height:8,borderRadius:'50%',background:'var(--c-data)',boxShadow:'0 0 6px var(--c-data)'}}></span>{t.shift.before.label}</div>
            <ul className="shift-verbs">
              {t.shift.before.items.map((it, i) => (
                <li key={i}>{it}</li>
              ))}
            </ul>
          </div>
          <div className="shift-arrow reveal">
            <ShiftArrow label={t.shift.arrow} />
          </div>
          <div className="shift-side after reveal">
            <div className="label"><span className="dot" style={{width:8,height:8,borderRadius:'50%',background:'var(--accent)',boxShadow:'0 0 6px var(--accent)'}}></span>{t.shift.after.label}</div>
            <ul className="shift-verbs">
              {t.shift.after.items.map((it, i) => (
                <li key={i}>{it}</li>
              ))}
            </ul>
          </div>
        </div>
      </section>

      {/* COMMAND CENTER */}
      <section id="panel">
        <div className="reveal">
          <div className="section-tag"><span className="dot"></span>{t.panel.tag}</div>
          <h2 className="section-title">{t.panel.title}</h2>
          <p className="section-lede">{t.panel.lede}</p>
        </div>
        <div className="panel-grid reveal">
          <div className="panel-col" data-col="you">
            <div className="panel-col-head"><span className="led"></span>{t.panel.columns.you.title.toUpperCase()}</div>
            <div className="panel-big">{t.panel.columns.you.big}</div>
            <div className="panel-title">{t.panel.columns.you.title}</div>
            <div className="panel-sub">{t.panel.columns.you.sub}</div>
            <p className="panel-desc">{t.panel.columns.you.desc}</p>
            <ul className="panel-tags">
              {t.panel.columns.you.tags.map((tg, i) => <li key={i}>{tg}</li>)}
            </ul>
          </div>
          <div className="panel-col" data-col="agents">
            <div className="panel-col-head"><span className="led"></span>{t.panel.columns.agents.title.toUpperCase()}</div>
            <div className="panel-big">{t.panel.columns.agents.big}</div>
            <div className="panel-title">{t.panel.columns.agents.title}</div>
            <div className="panel-sub">{t.panel.columns.agents.sub}</div>
            <p className="panel-desc">{t.panel.columns.agents.desc}</p>
            <div className="panel-chips">
              {t.panel.columns.agents.chips.map((c, i) => (
                <div key={i} className="panel-chip" data-k={c.k}>
                  <span className="led"></span>{c.name}
                </div>
              ))}
            </div>
          </div>
          <div className="panel-col" data-col="services">
            <div className="panel-col-head"><span className="led"></span>{t.panel.columns.services.title.toUpperCase()}</div>
            <div className="panel-big">{t.panel.columns.services.big}</div>
            <div className="panel-title">{t.panel.columns.services.title}</div>
            <div className="panel-sub">{t.panel.columns.services.sub}</div>
            <p className="panel-desc">{t.panel.columns.services.desc}</p>
            <div className="panel-chips">
              {t.panel.columns.services.chips.map((c, i) => (
                <div key={i} className="panel-chip" data-k={c.k}>
                  <span className="led"></span>{c.name}
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* CATALOG */}
      <Catalog t={t} />

      {/* COMO FUNCIONA */}
      <section id="como">
        <div className="reveal">
          <div className="section-tag" data-color="green"><span className="dot"></span>{t.como.tag}</div>
          <h2 className="section-title">{t.como.title}</h2>
          <p className="section-lede">{t.como.lede}</p>
        </div>
        <div className="steps">
          {t.como.steps.map((s, i) => (
            <div className="step reveal" key={i} style={{transitionDelay: `${i*100}ms`}}>
              <div className="step-num">STEP / {s.n}</div>
              <h3>{s.t}</h3>
              <p>{s.p}</p>
              <div className="step-illu">
                <StepIllu n={i} />
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* LIVE DEMO */}
      <section id="demo">
        <div className="reveal">
          <div className="section-tag" data-color="blue"><span className="dot"></span>{t.demo.tag}</div>
          <h2 className="section-title">{t.demo.title}</h2>
          <p className="section-lede">{t.demo.lede}</p>
        </div>
        <div className="reveal">
          <GraphDemo t={t} />
        </div>
      </section>

      {/* DOS CAMINOS */}
      <section id="paths">
        <div className="reveal">
          <div className="section-tag"><span className="dot"></span>{t.paths.tag}</div>
          <h2 className="section-title">{t.paths.title}</h2>
          <p className="section-lede">{t.paths.lede}</p>
        </div>
        <div className="paths">
          <div className="path-card reveal">
            <div className="path-tag"><span style={{width:6,height:6,borderRadius:'50%',background:'var(--c-trigger)',boxShadow:'0 0 6px var(--c-trigger)',display:'inline-block'}}></span>{t.paths.os.tag}</div>
            <h3>{t.paths.os.h}</h3>
            <div className="path-price"><b>{t.paths.os.price_pre}</b>{t.paths.os.price_post}</div>
            <p className="lede">{t.paths.os.lede}</p>
            <ul className="path-features">
              {t.paths.os.features.map((f, i) => <li key={i}>{f}</li>)}
            </ul>
            <div className="path-cta">
              <a href="#" className="btn" onClick={(e)=>e.preventDefault()}>{t.paths.os.cta}</a>
            </div>
          </div>
          <div className="path-card cloud reveal" style={{transitionDelay: '80ms'}}>
            <div className="path-tag"><span style={{width:6,height:6,borderRadius:'50%',background:'var(--accent)',boxShadow:'0 0 6px var(--accent)',display:'inline-block'}}></span>{t.paths.cloud.tag}</div>
            <h3>{t.paths.cloud.h}</h3>
            <div className="path-price"><b>{t.paths.cloud.price_pre} $49</b>{t.paths.cloud.price_post}</div>
            <p className="lede">{t.paths.cloud.lede}</p>
            <ul className="path-features">
              {t.paths.cloud.features.map((f, i) => <li key={i}>{f}</li>)}
            </ul>
            <div className="path-cta">
              <a href="#waitlist" className="btn primary">{t.paths.cloud.cta}</a>
            </div>
          </div>
        </div>
      </section>

      {/* WAITLIST */}
      <section id="waitlist" className="waitlist">
        <div className="reveal">
          <div className="mega-kanji">未来</div>
          <h2>{t.waitlist.title}</h2>
          <p>{t.waitlist.lede}</p>
          <Waitlist t={t} lang={lang} />
        </div>
      </section>

      {/* FOOTER */}
      <footer className="footer">
        <span className="brand">
          <span className="brand-logo" style={{fontSize: 14}}><span className="bl-data">DATA</span><span className="bl-kanji">未来</span></span>
        </span>
        <span>{t.footer.rights}</span>
        <span className="sep"></span>
        <span>{t.footer.made}</span>
      </footer>
    </div>
  );
}

// ─── Mount ──────────────────────────────────────────────────────────────────
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
