// Variant 2 — Dashboard Pulse
// 라이브 대시보드 (트래픽 그래프 + 보안 알림 + 마케팅 KPI) 가 살아 움직이고
// 마지막에 통합 뷰로 줌아웃하며 로고 등장.

function StatCard({ label, value, delta, color, children, width = 480, height = 240 }) {
  return (
    <div style={{
      width, height,
      background: 'rgba(255, 255, 255, 0.04)',
      backdropFilter: 'blur(12px)',
      border: `1px solid rgba(255,255,255,0.10)`,
      borderRadius: 18,
      padding: 28,
      display: 'flex', flexDirection: 'column', gap: 16,
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{
          fontSize: 14, fontWeight: 700, color: 'rgba(255,255,255,0.6)',
          letterSpacing: '0.12em', textTransform: 'uppercase',
        }}>
          {label}
        </div>
        {delta && (
          <div style={{
            fontSize: 14, fontWeight: 700, color, fontFamily: WP.fontMono,
          }}>{delta}</div>
        )}
      </div>
      <div style={{
        fontSize: 56, fontWeight: 800, color: WP.white,
        letterSpacing: '-0.03em', lineHeight: 1,
        fontFamily: WP.fontDisplay,
        fontFeatureSettings: '"tnum"',
      }}>{value}</div>
      <div style={{ flex: 1, position: 'relative' }}>{children}</div>
    </div>
  );
}

function LiveLine({ time, color, seed = 0, height = 60 }) {
  // animated line chart that scrolls
  const points = [];
  const N = 40;
  for (let i = 0; i < N; i++) {
    const phase = time * 1.4 + i * 0.4 + seed;
    const v = (Math.sin(phase) * 0.3 + Math.sin(phase * 1.7 + seed) * 0.2 + 0.5);
    points.push([i / (N - 1) * 320, height - v * height * 0.85]);
  }
  const d = points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p[0]} ${p[1]}`).join(' ');
  const fillD = d + ` L 320 ${height} L 0 ${height} Z`;
  return (
    <svg width="320" height={height} viewBox={`0 0 320 ${height}`} style={{ overflow: 'visible' }}>
      <defs>
        <linearGradient id={`line-${seed}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.35"/>
          <stop offset="100%" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={fillD} fill={`url(#line-${seed})`}/>
      <path d={d} stroke={color} strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
      {/* Trailing dot */}
      <circle cx={points[points.length - 1][0]} cy={points[points.length - 1][1]} r="3" fill={color}/>
      <circle cx={points[points.length - 1][0]} cy={points[points.length - 1][1]} r="6" fill={color} opacity="0.3"/>
    </svg>
  );
}

function ThreatLog({ time }) {
  const allItems = [
    { t: '14:02:11', m: 'SQLi 시도 차단', tag: 'BLOCK', c: '#E5484D' },
    { t: '14:02:14', m: '정상 트래픽', tag: 'PASS', c: '#12B981' },
    { t: '14:02:18', m: '봇 트래픽 차단', tag: 'BLOCK', c: '#E5484D' },
    { t: '14:02:22', m: '인증 성공', tag: 'PASS', c: '#12B981' },
    { t: '14:02:25', m: 'XSS 시도 차단', tag: 'BLOCK', c: '#E5484D' },
    { t: '14:02:28', m: '취약점 스캔', tag: 'SCAN', c: WP.cyan400 },
    { t: '14:02:31', m: '정상 트래픽', tag: 'PASS', c: '#12B981' },
    { t: '14:02:35', m: 'Path Traversal 차단', tag: 'BLOCK', c: '#E5484D' },
  ];
  const visibleCount = Math.min(allItems.length, Math.floor(time * 2.2) + 1);
  const items = allItems.slice(0, visibleCount).slice(-4);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontFamily: WP.fontMono, fontSize: 15 }}>
      {items.map((it, i) => (
        <div key={`${it.t}-${visibleCount - items.length + i}`} style={{
          display: 'flex', alignItems: 'center', gap: 12,
          opacity: i === items.length - 1 ? clamp((time * 2.2) % 1 + 0.4, 0, 1) : 1,
        }}>
          <span style={{ color: 'rgba(255,255,255,0.45)' }}>{it.t}</span>
          <span style={{
            fontSize: 12, padding: '2px 8px', borderRadius: 4,
            background: it.c + '22', color: it.c, fontWeight: 700,
          }}>{it.tag}</span>
          <span style={{ color: 'rgba(255,255,255,0.9)' }}>{it.m}</span>
        </div>
      ))}
    </div>
  );
}

function KeywordRanks({ time }) {
  const kws = [
    { k: '브랜드 키워드 A', from: 12, to: 3 },
    { k: '브랜드 키워드 B', from: 8, to: 2 },
    { k: '카테고리 검색', from: 23, to: 7 },
  ];
  const p = clamp((time - 0.5) / 2.5, 0, 1);
  const e = Easing.easeOutCubic(p);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {kws.map((kw, i) => {
        const v = Math.round(kw.from + (kw.to - kw.from) * e);
        return (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 16 }}>
            <span style={{ color: 'rgba(255,255,255,0.8)', fontWeight: 500 }}>{kw.k}</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ color: 'rgba(255,255,255,0.4)', fontSize: 13, textDecoration: 'line-through' }}>#{kw.from}</span>
              <span style={{ color: WP.orange400, fontWeight: 800, fontFamily: WP.fontMono, fontSize: 20 }}>#{v}</span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function PulseRing({ time, x, y, color }) {
  const period = 2.5;
  const t = (time % period) / period;
  return (
    <div style={{ position: 'absolute', left: x, top: y, pointerEvents: 'none' }}>
      <div style={{
        position: 'absolute', left: -1 - t * 50, top: -1 - t * 50,
        width: 2 + t * 100, height: 2 + t * 100,
        border: `1.5px solid ${color}`,
        borderRadius: '50%',
        opacity: (1 - t) * 0.7,
      }}/>
      <div style={{
        width: 8, height: 8, borderRadius: 4,
        background: color, boxShadow: `0 0 12px ${color}`,
      }}/>
    </div>
  );
}

function Variant2() {
  const T = useTime();

  // 0–2     intro: dashboard chrome assembles
  // 2–8     live data: graphs animate, log streams, KPI counts up
  // 8–11    zoom out + 3 panels merge → unified view
  // 11–15   logo + slogan hold

  const introP = clamp(T / 1.8, 0, 1);
  const introE = Easing.easeOutCubic(introP);

  const zoomStart = 8.0;
  const zoomEnd = 10.5;
  const zoom = clamp((T - zoomStart) / (zoomEnd - zoomStart), 0, 1);
  const zoomE = Easing.easeInOutCubic(zoom);

  // Camera scale: dashboard at scale 1, zooms out to 0.55 + bg fades to deep
  const camScale = 1 - zoomE * 0.5;
  const camY = zoomE * -120;

  // Logo phase
  const logoStart = 10.0;
  const logoP = clamp((T - logoStart) / 1.5, 0, 1);
  const logoE = Easing.easeOutCubic(logoP);

  const sloganP = clamp((T - 11.0) / 1.5, 0, 1);
  const sloganE = Easing.easeOutCubic(sloganP);

  // Loop bridge
  const outroP = clamp((T - 13.5) / 1.5, 0, 1);

  return (
    <div style={{ position: 'absolute', inset: 0, fontFamily: WP.font, overflow: 'hidden', background: WP.navy900 }}>
      {/* Deep gradient background */}
      <div style={{
        position: 'absolute', inset: 0,
        background: WP.gradHeroDeep,
      }}/>
      {/* Dot grid */}
      <DotGrid opacity={0.08} color={WP.white} spacing={48}/>
      {/* Subtle wave */}
      <div style={{ opacity: 0.5 + zoomE * 0.4 }}>
        <WaveBackdrop phase={(T * 0.03) % 1} opacity={0.5} color={WP.cyan500}/>
      </div>

      {/* Camera container */}
      <div style={{
        position: 'absolute', inset: 0,
        transform: `translateY(${camY}px) scale(${camScale})`,
        transformOrigin: 'center 45%',
        opacity: 1 - clamp((T - 10.5) / 1.5, 0, 1) * 0.85,
      }}>
        {/* Header bar */}
        <div style={{
          position: 'absolute',
          top: 70, left: 120, right: 120,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          opacity: introE,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
            <img src="assets/logo-wavepix-white.png" alt="" style={{ height: 48 }}/>
            <div style={{
              padding: '8px 16px', borderRadius: 999,
              background: 'rgba(0,168,217,0.12)',
              border: `1px solid ${WP.cyan500}55`,
              fontSize: 14, fontWeight: 700, color: WP.cyan400, letterSpacing: '0.08em',
            }}>
              <span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: 4, background: WP.cyan500, marginRight: 8, animation: 'pulse 1.5s ease-in-out infinite' }}/>
              LIVE · 24/365
            </div>
          </div>
          <div style={{
            display: 'flex', gap: 12, fontSize: 16, color: 'rgba(255,255,255,0.6)', fontFamily: WP.fontMono,
          }}>
            <span>UPTIME 99.99%</span>
            <span>·</span>
            <span>RT {(T * 1000 % 100 + 12).toFixed(0)}ms</span>
          </div>
        </div>

        {/* 3 Panels grid */}
        <div style={{
          position: 'absolute',
          top: 180, left: 120, right: 120,
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 28,
          opacity: introE,
        }}>
          {/* Panel 1 — Web traffic */}
          <div style={{ transform: `translateY(${(1 - introE) * 24}px)` }}>
            <StatCard
              label="WEB · 실시간 방문"
              value={Math.floor(1240 + Math.sin(T * 0.7) * 40 + T * 18).toLocaleString()}
              delta="↑ 18.4%"
              color={WP.blue400}
              width={550} height={520}
            >
              <div style={{ position: 'absolute', inset: 0, top: -10 }}>
                <svg width="100%" height="100%" viewBox="0 0 510 380" preserveAspectRatio="none" style={{ overflow: 'visible' }}>
                  <defs>
                    <linearGradient id="lg-web" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor={WP.blue400} stopOpacity="0.4"/>
                      <stop offset="100%" stopColor={WP.blue400} stopOpacity="0"/>
                    </linearGradient>
                  </defs>
                  {(() => {
                    const N = 60;
                    const pts = [];
                    for (let i = 0; i < N; i++) {
                      const phase = i * 0.25 + T * 0.4;
                      const v = (Math.sin(phase) * 0.25 + Math.sin(phase * 1.6 + 1) * 0.15 + Math.sin(phase * 0.6) * 0.1 + 0.55) * (1 + i / N * 0.4);
                      pts.push([i / (N - 1) * 510, 380 - clamp(v * 360, 0, 360)]);
                    }
                    const d = pts.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p[0]} ${p[1]}`).join(' ');
                    const fillD = d + ' L 510 380 L 0 380 Z';
                    return (
                      <>
                        <path d={fillD} fill="url(#lg-web)"/>
                        <path d={d} stroke={WP.blue400} strokeWidth="3" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                        <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="6" fill={WP.cyan400}/>
                        <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="14" fill={WP.cyan400} opacity="0.3"/>
                      </>
                    );
                  })()}
                </svg>
              </div>
            </StatCard>
          </div>

          {/* Panel 2 — Security */}
          <div style={{ transform: `translateY(${(1 - introE) * 36}px)`, transition: 'transform 0.6s' }}>
            <StatCard
              label="SECURITY · 위협 차단"
              value={Math.floor(847 + T * 4)}
              delta="● 실시간"
              color="#12B981"
              width={550} height={520}
            >
              <ThreatLog time={T - 1.5}/>
              {/* radar arc */}
              <div style={{ position: 'absolute', right: 10, top: -6, width: 100, height: 100 }}>
                <svg viewBox="0 0 100 100" width="100" height="100">
                  <circle cx="50" cy="50" r="40" stroke="rgba(255,255,255,0.12)" strokeWidth="1" fill="none"/>
                  <circle cx="50" cy="50" r="26" stroke="rgba(255,255,255,0.12)" strokeWidth="1" fill="none"/>
                  <circle cx="50" cy="50" r="12" stroke="rgba(255,255,255,0.12)" strokeWidth="1" fill="none"/>
                  <line x1="50" y1="50"
                    x2={50 + Math.cos(T * 1.8) * 40}
                    y2={50 + Math.sin(T * 1.8) * 40}
                    stroke={WP.cyan500} strokeWidth="2" strokeLinecap="round"/>
                  <circle cx="50" cy="50" r="3" fill={WP.cyan500}/>
                </svg>
              </div>
            </StatCard>
          </div>

          {/* Panel 3 — Marketing */}
          <div style={{ transform: `translateY(${(1 - introE) * 48}px)` }}>
            <StatCard
              label="MARKETING · 노출 순위"
              value={`#${Math.max(2, Math.round(12 - clamp((T - 1) / 4, 0, 1) * 9))}`}
              delta={`▲ ${Math.round(clamp((T - 1) / 4, 0, 1) * 9)}계단`}
              color={WP.orange400}
              width={550} height={520}
            >
              <KeywordRanks time={T}/>
              <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0 }}>
                <svg width="100%" height="80" viewBox="0 0 510 80" preserveAspectRatio="none">
                  {[0, 1, 2, 3, 4, 5, 6].map(i => {
                    const h = 18 + Math.sin(i + T * 0.5) * 8 + i * 6;
                    return (
                      <rect key={i} x={i * 72 + 8} y={80 - h} width={56} height={h}
                        fill={WP.orange500} opacity={0.4 + i * 0.08} rx="3"/>
                    );
                  })}
                </svg>
              </div>
            </StatCard>
          </div>
        </div>

        {/* Pulse rings on each panel */}
        {introE > 0.6 && [
          { x: 640, y: 198, c: WP.cyan400 },
          { x: 1150, y: 198, c: '#12B981' },
          { x: 1660, y: 198, c: WP.orange500 },
        ].map((p, i) => (
          <PulseRing key={i} time={T + i * 0.5} x={p.x} y={p.y} color={p.c}/>
        ))}
      </div>

      {/* Convergence sweep */}
      {T > 7.8 && T < 10.5 && (
        <div style={{ opacity: Math.sin(clamp((T - 7.8) / 2.7, 0, 1) * Math.PI) * 0.7, position: 'absolute', inset: 0 }}>
          <SignatureWave x={0} y={440} width={1920} height={220} progress={clamp((T - 7.8) / 1.4, 0, 1)} color={WP.cyan500} strokeWidth={3}/>
        </div>
      )}

      {/* Logo */}
      <div style={{
        position: 'absolute',
        left: 960, top: 440,
        transform: `translate(-50%, -50%) translateY(${(1 - logoE) * 32}px)`,
        opacity: logoE,
        textAlign: 'center',
      }}>
        <img src="assets/logo-wavepix-white.png" alt="WAVEPIX"
          style={{
            height: 180,
            filter: `drop-shadow(0 8px 36px rgba(0, 168, 217, ${0.5 * logoE}))`,
          }}/>
      </div>

      {/* Slogan */}
      <div style={{
        position: 'absolute',
        left: 960, top: 620,
        transform: `translate(-50%, 0) translateY(${(1 - sloganE) * 16}px)`,
        opacity: sloganE,
        textAlign: 'center',
        width: 1700,
      }}>
        <div style={{
          fontSize: 72, fontWeight: 800, color: WP.white,
          letterSpacing: '-0.04em', lineHeight: 1.2,
        }}>
          AI로 중심을 잡고, <span style={{ color: WP.cyan400 }}>한발 앞서갑니다.</span>
        </div>
        <div style={{
          marginTop: 28,
          fontSize: 22, color: 'rgba(255,255,255,0.7)',
          letterSpacing: '0.16em', fontWeight: 700,
          fontFamily: WP.fontMono,
        }}>
          WEB · SECURITY · MARKETING — POWERED BY AI
        </div>
      </div>

      <style>{`@keyframes pulse { 0%,100% { opacity: 1 } 50% { opacity: 0.3 } }`}</style>
    </div>
  );
}

window.Variant2 = Variant2;
