/* ============================================================
   HERO ANIMATION — chart morphs into Vero app UI
   ============================================================ */
const { useState, useEffect, useRef, useMemo } = React;

const HeroAnimation = () => {
  // phase 0→1 cycles: chart (0-0.55) → morph (0.55-0.7) → app (0.7-1)
  const [t, setT] = useState(0);
  const reqRef = useRef();
  const startRef = useRef();

  useEffect(() => {
    const DUR = 9000; // ms per cycle
    const tick = (now) => {
      if (!startRef.current) startRef.current = now;
      const e = (now - startRef.current) / DUR;
      setT(e % 1);
      reqRef.current = requestAnimationFrame(tick);
    };
    reqRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(reqRef.current);
  }, []);

  // phases
  const chartT  = Math.min(1, t / 0.5);                    // 0-0.5: chart draws
  const morphT  = Math.max(0, Math.min(1, (t - 0.5) / 0.2)); // 0.5-0.7: morph
  const appT    = Math.max(0, Math.min(1, (t - 0.65) / 0.3)); // 0.65-0.95: app visible

  const chartOpacity = t < 0.55 ? 1 : Math.max(0, 1 - (t - 0.55) / 0.15);
  const appOpacity = appT;
  const phoneScale = 0.6 + appT * 0.4;
  const phoneY = (1 - appT) * 20;

  // candlestick data
  const candles = useMemo(() => {
    const rng = (s => () => (s = (s * 9301 + 49297) % 233280) / 233280)(3);
    const out = [];
    let p = 50;
    for (let i = 0; i < 40; i++) {
      const o = p;
      const c = o + (rng() - 0.48) * 4;
      const hi = Math.max(o, c) + rng() * 1.5;
      const lo = Math.min(o, c) - rng() * 1.5;
      out.push({ o, c, hi, lo });
      p = c;
    }
    return out;
  }, []);

  const W = 560, H = 400;
  const minV = Math.min(...candles.map(c => c.lo)) - 1;
  const maxV = Math.max(...candles.map(c => c.hi)) + 1;
  const yOf = v => 30 + (maxV - v) / (maxV - minV) * (H - 60);
  const cw = (W - 40) / candles.length;

  // SMA smooth line
  const sma = candles.map((c, i) => {
    const s = candles.slice(Math.max(0, i - 4), i + 1);
    return s.reduce((a, b) => a + b.c, 0) / s.length;
  });

  return (
    <div style={{ position: 'relative', width: '100%', height: '100%' }}>
      {/* =============== CHART LAYER =============== */}
      <div style={{
        position: 'absolute', inset: 0,
        opacity: chartOpacity,
        transition: 'opacity 0.3s',
      }}>
        <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" style={{ overflow: 'visible' }}>
          <defs>
            <linearGradient id="bgGlow" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" stopColor="#6B8AE4" stopOpacity="0.08"/>
              <stop offset="1" stopColor="#6B8AE4" stopOpacity="0"/>
            </linearGradient>
            <linearGradient id="smaLine" x1="0" y1="0" x2="1" y2="0">
              <stop offset="0" stopColor="#4A6BC4"/>
              <stop offset="1" stopColor="#AAC0FF"/>
            </linearGradient>
          </defs>
          {/* grid */}
          <g stroke="rgba(107,138,228,0.06)" strokeDasharray="3 5">
            {[0, 1, 2, 3, 4].map(i => (
              <line key={i} x1="0" x2={W} y1={30 + i * (H - 60) / 4} y2={30 + i * (H - 60) / 4}/>
            ))}
          </g>
          {/* price labels */}
          <g fill="#52525B" fontSize="10" fontFamily="JetBrains Mono, monospace" textAnchor="end">
            <text x={W - 4} y="34">241.47</text>
            <text x={W - 4} y={H / 2}>240.67</text>
            <text x={W - 4} y={H - 30}>239.09</text>
          </g>
          {/* candles — reveal progressively */}
          {candles.map((c, i) => {
            const pct = i / candles.length;
            if (pct > chartT) return null;
            const x = 20 + i * cw;
            const up = c.c >= c.o;
            const col = up ? '#10B981' : '#EF4444';
            return (
              <g key={i}>
                <line x1={x + cw / 2} x2={x + cw / 2} y1={yOf(c.hi)} y2={yOf(c.lo)} stroke={col} strokeWidth="1"/>
                <rect x={x + 1} y={yOf(Math.max(c.o, c.c))} width={cw - 2} height={Math.max(1.5, Math.abs(yOf(c.c) - yOf(c.o)))} fill={col} opacity="0.95"/>
              </g>
            );
          })}
          {/* SMA line */}
          <polyline
            fill="none"
            stroke="url(#smaLine)"
            strokeWidth="2"
            strokeLinecap="round"
            points={sma.slice(0, Math.floor(chartT * sma.length)).map((v, i) => `${20 + i * cw + cw / 2},${yOf(v)}`).join(' ')}
          />
          {/* glow under SMA */}
          <polyline
            fill="none"
            stroke="#6B8AE4"
            strokeWidth="8"
            strokeLinecap="round"
            opacity="0.15"
            points={sma.slice(0, Math.floor(chartT * sma.length)).map((v, i) => `${20 + i * cw + cw / 2},${yOf(v)}`).join(' ')}
          />
          {/* signal dot at last position */}
          {chartT > 0.2 && (() => {
            const idx = Math.min(sma.length - 1, Math.floor(chartT * sma.length));
            const x = 20 + idx * cw + cw / 2;
            const y = yOf(sma[idx]);
            return (
              <g>
                <circle cx={x} cy={y} r="10" fill="#6B8AE4" opacity="0.15"/>
                <circle cx={x} cy={y} r="4.5" fill="#AAC0FF"/>
              </g>
            );
          })()}
          {/* timeframe pill */}
          <g transform={`translate(${W - 80}, 8)`}>
            <rect width="70" height="22" rx="4" fill="rgba(39,39,42,0.8)"/>
            <text x="35" y="15" fill="#A1A1AA" fontSize="10" fontFamily="JetBrains Mono, monospace" fontWeight="600" textAnchor="middle">5 min</text>
          </g>
        </svg>
      </div>

      {/* =============== MORPH RAYS =============== */}
      {morphT > 0 && morphT < 1 && (
        <div style={{
          position: 'absolute', inset: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          pointerEvents: 'none',
        }}>
          <div style={{
            width: 240, height: 240, borderRadius: '50%',
            background: 'radial-gradient(circle, rgba(107,138,228,0.5), transparent 70%)',
            transform: `scale(${1 + morphT * 2})`,
            opacity: (1 - morphT) * 0.8,
          }}/>
        </div>
      )}

      {/* =============== APP LAYER =============== */}
      <div style={{
        position: 'absolute', inset: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        opacity: appOpacity,
        transform: `translateY(${phoneY}px) scale(${phoneScale})`,
        transition: 'none',
      }}>
        <PhoneMock/>
      </div>
    </div>
  );
};

/* ============================================================
   PHONE MOCK — real Vero Home screen (mirrors mobile/app/(tabs)/index.tsx)
   ============================================================ */
const PhoneMock = () => (
  <div style={{
    width: 300, height: 600,
    borderRadius: 42,
    background: '#000',
    border: '8px solid #18181B',
    boxShadow: '0 40px 90px rgba(0,0,0,0.5), 0 0 60px rgba(107,138,228,0.2), 0 0 0 1px rgba(255,255,255,0.08)',
    position: 'relative',
    overflow: 'hidden',
  }}>
    {/* notch */}
    <div style={{
      position: 'absolute', top: 8, left: '50%', transform: 'translateX(-50%)',
      width: 100, height: 28, borderRadius: 20, background: '#000', zIndex: 5,
    }}/>
    {/* subtle chart background (ChartBackground component) */}
    <div style={{
      position: 'absolute', inset: 0,
      background: '#09090B',
      overflow: 'hidden',
    }}>
      <svg viewBox="0 0 300 390" style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '65%', opacity: 0.35 }} preserveAspectRatio="none">
        <defs>
          <linearGradient id="cbg" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#6B8AE4" stopOpacity="0.25"/>
            <stop offset="100%" stopColor="#6B8AE4" stopOpacity="0"/>
          </linearGradient>
        </defs>
        <path d="M0,260 L20,240 L40,250 L60,220 L80,230 L100,200 L120,210 L140,180 L160,170 L180,190 L200,150 L220,160 L240,130 L260,140 L280,110 L300,120 L300,390 L0,390 Z" fill="url(#cbg)"/>
        <path d="M0,260 L20,240 L40,250 L60,220 L80,230 L100,200 L120,210 L140,180 L160,170 L180,190 L200,150 L220,160 L240,130 L260,140 L280,110 L300,120" fill="none" stroke="#6B8AE4" strokeOpacity="0.5" strokeWidth="1"/>
      </svg>
    </div>
    <div style={{
      position: 'absolute', inset: 0,
      padding: '52px 16px 10px',
      display: 'flex', flexDirection: 'column', gap: 12,
    }}>
      {/* topbar: menu + streak */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{
          width: 30, height: 30, borderRadius: 15,
          background: 'rgba(24,24,27,0.6)',
          border: '1px solid rgba(107,138,228,0.1)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#A1A1AA" strokeWidth="2.2" strokeLinecap="round"><path d="M3 7h18M3 12h18M3 17h18"/></svg>
        </div>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 5,
          background: 'linear-gradient(135deg,#F59E0B,#EA580C)',
          padding: '4px 10px', borderRadius: 9999,
          color: '#fff', fontWeight: 700, fontSize: 10,
          boxShadow: '0 4px 14px rgba(245,158,11,.3)',
        }}>
          <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M13.5 2c2 4 5 6 5 10 0 3.5-3 6-6 6s-6-2.5-6-6c0-1.5.5-3 1-4 1 2 2 2 2 1s-1-3 1-6c1 2 2 2 3-1z"/></svg>
          Day 7
        </div>
      </div>

      {/* hero card: logo + Vero title + welcome + rank badge */}
      <div style={{
        background: 'rgba(20,22,36,0.85)',
        border: '1px solid rgba(107,138,228,0.12)',
        borderRadius: 14,
        padding: '14px 16px',
        textAlign: 'center',
        backdropFilter: 'blur(12px)',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8 }}>
          <svg width="26" height="24" viewBox="0 0 62 58" fill="none">
            <path d="M 6 8 L 26 50 L 52 4" stroke="url(#hv1)" strokeWidth="5.5" strokeLinecap="round" strokeLinejoin="round"/>
            <path d="M 1 36 L 10 36 L 16 42 L 24 26 L 30 34 L 36 24 L 42 28 L 56 16" stroke="url(#hv2)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" opacity="0.45"/>
            <circle cx="52" cy="4" r="3.5" fill="#8BA4EE"/>
            <circle cx="52" cy="4" r="8" fill="#6B8AE4" opacity="0.15"/>
            <defs>
              <linearGradient id="hv1" x1="6" y1="50" x2="52" y2="4">
                <stop offset="0%" stopColor="#4A6BC4"/>
                <stop offset="55%" stopColor="#6B8AE4"/>
                <stop offset="100%" stopColor="#8BA4EE"/>
              </linearGradient>
              <linearGradient id="hv2" x1="1" y1="36" x2="56" y2="16">
                <stop offset="0%" stopColor="#4A6BC4" stopOpacity="0.2"/>
                <stop offset="50%" stopColor="#6B8AE4"/>
                <stop offset="100%" stopColor="#8BA4EE" stopOpacity="0.3"/>
              </linearGradient>
            </defs>
          </svg>
          <span style={{ fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: 24, letterSpacing: '-0.5px' }}>Vero</span>
        </div>
        <div style={{ fontSize: 10.5, color: '#A1A1AA', marginTop: 4 }}>
          Welcome back, <span style={{ color: '#8BA4EE', fontWeight: 500 }}>Trader</span>
        </div>
        <div style={{
          display: 'inline-block', marginTop: 6,
          padding: '2px 9px', borderRadius: 9999,
          background: 'rgba(245, 158, 11, 0.12)',
          color: '#F59E0B', fontSize: 9, fontWeight: 600,
        }}>Chartist</div>
      </div>

      {/* stats card: XP bar + 4 stat cells */}
      <div style={{
        background: 'rgba(20,22,36,0.85)',
        border: '1px solid rgba(107,138,228,0.08)',
        borderRadius: 14,
        padding: 12,
        backdropFilter: 'blur(12px)',
      }}>
        {/* XP header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 5 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <svg width="10" height="10" viewBox="0 0 24 24" fill="#F59E0B"><path d="M12 2l8 4v6c0 5-3.5 9.5-8 10-4.5-.5-8-5-8-10V6l8-4z"/></svg>
            <span style={{ fontSize: 10, color: '#F59E0B', fontWeight: 600 }}>Chartist</span>
          </div>
          <span style={{ fontSize: 9, color: '#71717A' }}>Analyst</span>
        </div>
        {/* XP bar */}
        <div style={{ height: 5, borderRadius: 3, background: 'rgba(255,255,255,0.08)', overflow: 'hidden' }}>
          <div style={{ height: '100%', width: '62%', background: '#F59E0B', borderRadius: 3 }}/>
        </div>
        <div style={{ fontSize: 9, color: '#A1A1AA', marginTop: 3 }}>2,340 / 3,800 XP</div>
        {/* 2x2 stat grid */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', marginTop: 10, rowGap: 8 }}>
          {[['74%','Accuracy'],['12','Best Streak'],['148','Rounds'],['6','Level']].map(([v,l])=>(
            <div key={l} style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 15, fontWeight: 700, color: '#F4F4F5', lineHeight: 1 }}>{v}</div>
              <div style={{ fontSize: 9, color: '#A1A1AA', marginTop: 2 }}>{l}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Play button */}
      <div style={{
        background: 'linear-gradient(90deg, #5B78D6, #7E9DF0)',
        borderRadius: 14, padding: '14px 16px',
        display: 'flex', alignItems: 'center', gap: 10,
        boxShadow: '0 10px 24px rgba(107,138,228,0.4)',
      }}>
        <div style={{
          width: 30, height: 30, borderRadius: 15,
          background: 'rgba(255,255,255,0.22)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="#fff"><path d="M7 5v14l12-7z"/></svg>
        </div>
        <div style={{ flex: 1, color: '#fff' }}>
          <div style={{ fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: 15 }}>Play</div>
          <div style={{ fontSize: 9.5, opacity: 0.85 }}>Free play or survival mode</div>
        </div>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" opacity="0.8"><path d="M9 6l6 6-6 6"/></svg>
      </div>

      {/* 2×2 secondary grid: Daily / Dashboard / Learn / Feedback */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        {[
          { t:'Daily',     d:'Same charts for all', icon:'trophy',   bg:'rgba(245, 158, 11, 0.12)', c:'#F59E0B' },
          { t:'Dashboard', d:'Deep analytics',      icon:'analytics',bg:'rgba(96, 165, 250, 0.12)', c:'#60A5FA' },
          { t:'Learn',     d:'Patterns & concepts', icon:'book',     bg:'rgba(167, 139, 250, 0.12)',c:'#A78BFA' },
          { t:'Feedback',  d:'Share your thoughts', icon:'chat',     bg:'rgba(245, 158, 11, 0.12)', c:'#F59E0B' },
        ].map((it) => (
          <div key={it.t} style={{
            background: 'rgba(20,22,36,0.85)',
            border: '1px solid rgba(107,138,228,0.08)',
            borderRadius: 12,
            padding: '10px 6px',
            textAlign: 'center',
            backdropFilter: 'blur(12px)',
          }}>
            <div style={{
              width: 28, height: 28, borderRadius: 8,
              background: it.bg,
              margin: '0 auto 5px',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: it.c,
            }}>
              {it.icon === 'trophy' && <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><path d="M7 3h10v3a5 5 0 0 1-3 4.58V13h3v2H7v-2h3v-2.42A5 5 0 0 1 7 6V3zm0 5h10"/></svg>}
              {it.icon === 'analytics' && <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3v18h18M7 14l3-3 3 3 5-5"/></svg>}
              {it.icon === 'book' && <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><path d="M4 4h6a3 3 0 0 1 3 3v13a2 2 0 0 0-2-2H4V4zm16 0v14h-7a2 2 0 0 0-2 2V7a3 3 0 0 1 3-3h6z"/></svg>}
              {it.icon === 'chat' && <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><path d="M4 4h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H8l-4 4V6a2 2 0 0 1 2-2z"/></svg>}
            </div>
            <div style={{ fontWeight: 600, fontSize: 11, color: '#F4F4F5' }}>{it.t}</div>
            <div style={{ fontSize: 8.5, color: '#A1A1AA', marginTop: 1 }}>{it.d}</div>
          </div>
        ))}
      </div>

      <div style={{ textAlign: 'center', fontSize: 8.5, color: '#52525B', marginTop: 2 }}>
        Not financial advice
      </div>
    </div>
  </div>
);

window.HeroAnimation = HeroAnimation;
