// Variant 3 — Wave Reveal
// Brand wave가 화면을 가로지르며 3개 영역(Web → Security → Marketing)을
// 차례로 reveal. 마지막에 합쳐지며 로고 등장. 추상 모션 중심.

function ServiceTile({ label, korLabel, desc, icon, color, accent, children, x, y, scale = 1, opacity = 1 }) {
  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      transform: `translate(-50%, -50%) scale(${scale})`,
      opacity,
      width: 900,
      pointerEvents: 'none',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 22, marginBottom: 28,
      }}>
        <div style={{
          width: 88, height: 88, borderRadius: 20,
          background: color,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: WP.white,
          boxShadow: `0 12px 36px ${color}66`,
        }}>
          {icon}
        </div>
        <div>
          <div style={{ fontSize: 18, fontWeight: 700, color: accent, letterSpacing: '0.18em', textTransform: 'uppercase', fontFamily: WP.fontMono }}>
            {label}
          </div>
          <div style={{ fontSize: 64, fontWeight: 800, color: WP.white, letterSpacing: '-0.03em', lineHeight: 1.1, marginTop: 6 }}>
            {korLabel}
          </div>
        </div>
      </div>
      <div style={{
        fontSize: 28, color: 'rgba(255,255,255,0.8)', lineHeight: 1.55,
        letterSpacing: '-0.01em', maxWidth: 780,
        marginBottom: 28, fontWeight: 500,
      }}>
        {desc}
      </div>
      {children}
    </div>
  );
}

function FeatureChips({ items, color }) {
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}>
      {items.map((it, i) => (
        <div key={i} style={{
          padding: '12px 22px',
          background: 'rgba(255,255,255,0.06)',
          border: `1.5px solid ${color}66`,
          borderRadius: 999,
          fontSize: 20, color: 'rgba(255,255,255,0.9)', fontWeight: 600,
        }}>
          {it}
        </div>
      ))}
    </div>
  );
}

// Big wave layer — fills the canvas with a flowing wave that morphs.
function BigWave({ time, intensity = 1, baseColor = WP.blue600, accentColor = WP.cyan500, yCenter = 540, opacity = 1, phaseOffset = 0 }) {
  const W = 1920;
  const H = 1080;
  const buildPath = (offsetY, freq, amp, phase) => {
    const N = 40;
    const pts = [];
    for (let i = 0; i <= N; i++) {
      const x = (i / N) * W;
      const y = yCenter + offsetY + Math.sin((i / N) * freq * Math.PI * 2 + phase) * amp * intensity;
      pts.push([x, y]);
    }
    let d = `M ${pts[0][0]} ${pts[0][1]}`;
    for (let i = 1; i < pts.length; i++) {
      const cpx = (pts[i - 1][0] + pts[i][0]) / 2;
      d += ` Q ${pts[i - 1][0]} ${pts[i - 1][1]}, ${cpx} ${(pts[i - 1][1] + pts[i][1]) / 2}`;
    }
    d += ` L ${W} ${H} L 0 ${H} Z`;
    return d;
  };

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ position: 'absolute', inset: 0, opacity }} preserveAspectRatio="none">
      <defs>
        <linearGradient id="bw1" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor={baseColor} stopOpacity="0.9"/>
          <stop offset="100%" stopColor={accentColor} stopOpacity="0.7"/>
        </linearGradient>
        <linearGradient id="bw2" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0%" stopColor={accentColor} stopOpacity="0.4"/>
          <stop offset="50%" stopColor={accentColor} stopOpacity="0.9"/>
          <stop offset="100%" stopColor={accentColor} stopOpacity="0.3"/>
        </linearGradient>
      </defs>
      {/* Filled wave */}
      <path d={buildPath(0, 2, 70, time * 1.2 + phaseOffset)} fill="url(#bw1)" opacity="0.85"/>
      {/* Stroke wave above */}
      <path d={buildPath(-30, 2.4, 60, time * 1.5 + phaseOffset + 0.6).replace(/L 1920 1080 L 0 1080 Z/, '')}
        stroke="url(#bw2)" strokeWidth="2.5" fill="none" opacity="0.9"/>
      <path d={buildPath(-60, 1.8, 50, time * 1.0 + phaseOffset + 1.2).replace(/L 1920 1080 L 0 1080 Z/, '')}
        stroke="url(#bw2)" strokeWidth="1.5" fill="none" opacity="0.6"/>
    </svg>
  );
}

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

  // Timing — sequential reveal of 3 services then unite
  // 0–1   intro (wave entering, dark canvas)
  // 1–4   Web reveal
  // 4–7   Security reveal (wave sweeps from right)
  // 7–10  Marketing reveal
  // 10–13 wave swells, all 3 collapse into logo
  // 13–15 logo + slogan hold

  // helper: per-service window with cross-fade
  const window_ = (start, end) => {
    const fadeIn = clamp((T - start) / 0.7, 0, 1);
    const fadeOut = 1 - clamp((T - end) / 0.7, 0, 1);
    return Math.min(fadeIn, fadeOut);
  };

  const webOp = window_(1.2, 4.2);
  const secOp = window_(4.0, 7.2);
  const mktOp = window_(7.0, 10.0);

  const webEntry = clamp((T - 1.0) / 0.8, 0, 1);
  const secEntry = clamp((T - 3.8) / 0.8, 0, 1);
  const mktEntry = clamp((T - 6.8) / 0.8, 0, 1);

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

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

  // Wave intensity — swells at unity moment
  const swellP = clamp((T - 9.5) / 2.0, 0, 1);
  const swell = Math.sin(swellP * Math.PI) * 0.6 + 1;

  // wave colors transition between scenes
  const sceneIdx = T < 4 ? 0 : T < 7 ? 1 : T < 10 ? 2 : 3;
  const sceneColors = [
    { base: WP.blue600, accent: WP.cyan500 },     // web
    { base: WP.navy600, accent: WP.blue400 },     // security
    { base: WP.blue700, accent: WP.orange500 },   // marketing
    { base: WP.blue600, accent: WP.cyan500 },     // unity
  ];
  // smooth interpolation between scene colors based on T windows
  const colorAt = (t) => {
    if (t < 4) return sceneColors[0];
    if (t < 4.5) {
      const k = (t - 4) / 0.5;
      return {
        base: mixColor(sceneColors[0].base, sceneColors[1].base, k),
        accent: mixColor(sceneColors[0].accent, sceneColors[1].accent, k),
      };
    }
    if (t < 7) return sceneColors[1];
    if (t < 7.5) {
      const k = (t - 7) / 0.5;
      return {
        base: mixColor(sceneColors[1].base, sceneColors[2].base, k),
        accent: mixColor(sceneColors[1].accent, sceneColors[2].accent, k),
      };
    }
    if (t < 10) return sceneColors[2];
    if (t < 10.5) {
      const k = (t - 10) / 0.5;
      return {
        base: mixColor(sceneColors[2].base, sceneColors[3].base, k),
        accent: mixColor(sceneColors[2].accent, sceneColors[3].accent, k),
      };
    }
    return sceneColors[3];
  };
  const colors = colorAt(T);

  return (
    <div style={{ position: 'absolute', inset: 0, fontFamily: WP.font, overflow: 'hidden', background: WP.navy900 }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: WP.gradHeroDeep,
      }}/>

      <DotGrid opacity={0.07} color={WP.white} spacing={48}/>

      {/* Big back wave (slow) */}
      <BigWave time={T * 0.6} intensity={0.9 * swell} baseColor={colors.base} accentColor={colors.accent} yCenter={780} opacity={0.5}/>
      {/* Front wave */}
      <BigWave time={T * 0.9 + 1.3} intensity={1.0 * swell} baseColor={colors.base} accentColor={colors.accent} yCenter={920} opacity={0.85}/>

      {/* Floating wave streaks */}
      <SignatureWave x={0} y={140} width={1920} height={180} progress={clamp(T / 1.5, 0, 1)} color={colors.accent} strokeWidth={2}/>

      {/* Section index ribbon */}
      <div style={{
        position: 'absolute', top: 80, left: 120,
        display: 'flex', gap: 22, alignItems: 'center',
        opacity: clamp(T - 0.5, 0, 1) * (1 - clamp((T - 10.0) / 1.0, 0, 1)),
      }}>
        {['WEB', 'SECURITY', 'MARKETING'].map((l, i) => {
          const active = sceneIdx === i;
          return (
            <React.Fragment key={i}>
              <div style={{
                fontSize: 18, fontWeight: 700, letterSpacing: '0.18em',
                color: active ? WP.cyan400 : 'rgba(255,255,255,0.35)',
                fontFamily: WP.fontMono,
                transition: 'color 300ms',
              }}>
                {String(i + 1).padStart(2, '0')} · {l}
              </div>
              {i < 2 && <div style={{
                width: 36, height: 1.5, background: 'rgba(255,255,255,0.2)',
              }}/>}
            </React.Fragment>
          );
        })}
      </div>

      {/* Counter */}
      <div style={{
        position: 'absolute', top: 80, right: 120,
        fontSize: 18, fontWeight: 700, letterSpacing: '0.16em',
        color: 'rgba(255,255,255,0.45)', fontFamily: WP.fontMono,
        opacity: clamp(T - 0.5, 0, 1) * (1 - clamp((T - 10.0) / 1.0, 0, 1)),
      }}>
        WAVEPIX · 2026
      </div>

      {/* Service 1 — Web */}
      <div style={{ opacity: webOp }}>
        <ServiceTile
          x={960} y={540}
          scale={0.94 + 0.06 * Easing.easeOutCubic(webEntry)}
          label="01 · Web"
          korLabel="홈페이지 관리"
          accent={WP.cyan400}
          color={WP.blue600}
          icon={<svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15 15 0 010 20M12 2a15 15 0 000 20"/></svg>}
          desc={"브랜드를 빠르게 살리는 홈페이지 구축과 안정적인 운영·유지보수를 한 팀에서 제공합니다."}
        >
          <FeatureChips color={WP.cyan500} items={['반응형 구축', '콘텐츠 운영', '유지보수', 'SEO 최적화']}/>
        </ServiceTile>
      </div>

      {/* Service 2 — Security */}
      <div style={{ opacity: secOp }}>
        <ServiceTile
          x={960} y={540}
          scale={0.94 + 0.06 * Easing.easeOutCubic(secEntry)}
          label="02 · Security"
          korLabel="AI 보안 관제"
          accent="#12B981"
          color={WP.navy700}
          icon={<svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/></svg>}
          desc={"AI·머신러닝 기반 탐지 엔진이 24/365 실시간으로 위협을 차단하고, 침해 사고에 즉시 대응합니다."}
        >
          <FeatureChips color="#12B981" items={['24/365 관제', 'AI 위협 탐지', '실시간 차단', '침해 대응']}/>
        </ServiceTile>
      </div>

      {/* Service 3 — Marketing */}
      <div style={{ opacity: mktOp }}>
        <ServiceTile
          x={960} y={540}
          scale={0.94 + 0.06 * Easing.easeOutCubic(mktEntry)}
          label="03 · Marketing"
          korLabel="마케팅 AI"
          accent={WP.orange400}
          color={WP.orange500}
          icon={<svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 11l18-7v16l-18-7v-2z"/><path d="M11 14v6a2 2 0 002 2h0a2 2 0 002-2v-3"/></svg>}
          desc={"AI가 키워드 트렌드를 분석하고 콘텐츠 초안을 생성합니다. 검색 노출과 광고 성과를 한 화면에서 측정합니다."}
        >
          <FeatureChips color={WP.orange500} items={['AI 콘텐츠', '키워드 분석', '리포트 자동화', '검색 노출']}/>
        </ServiceTile>
      </div>

      {/* Convergence flash */}
      {T > 9.8 && T < 12.5 && (
        <div style={{
          position: 'absolute',
          left: 960, top: 540,
          transform: 'translate(-50%, -50%)',
          width: 1600, height: 1600,
          borderRadius: '50%',
          background: `radial-gradient(circle, ${WP.cyan500}66 0%, ${WP.blue600}22 30%, transparent 60%)`,
          opacity: Math.sin(clamp((T - 9.8) / 2.7, 0, 1) * Math.PI) * 0.85,
          pointerEvents: 'none',
        }}/>
      )}

      {/* Logo */}
      <div style={{
        position: 'absolute',
        left: 960, top: 430,
        transform: `translate(-50%, -50%) translateY(${(1 - logoE) * 32}px) scale(${0.92 + logoE * 0.08})`,
        opacity: logoE,
        textAlign: 'center',
      }}>
        <img src="assets/logo-wavepix-white.png" alt="WAVEPIX"
          style={{
            height: 192,
            filter: `drop-shadow(0 12px 40px rgba(0, 168, 217, ${0.55 * 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: 26, color: 'rgba(255,255,255,0.7)',
          letterSpacing: '0.18em', fontWeight: 700,
          fontFamily: WP.fontMono,
        }}>
          wavepix.co.kr
        </div>
      </div>
    </div>
  );
}

// utility: linear color blend in hex
function mixColor(a, b, t) {
  const ah = parseInt(a.slice(1), 16);
  const bh = parseInt(b.slice(1), 16);
  const ar = (ah >> 16) & 255, ag = (ah >> 8) & 255, ab = ah & 255;
  const br = (bh >> 16) & 255, bg = (bh >> 8) & 255, bb = bh & 255;
  const r = Math.round(ar + (br - ar) * t);
  const g = Math.round(ag + (bg - ag) * t);
  const bl = Math.round(ab + (bb - ab) * t);
  return '#' + [r, g, bl].map(v => v.toString(16).padStart(2, '0')).join('');
}

window.Variant3 = Variant3;
