/* Embarc explainer video — "From Struggling to Scaling"
   Scenes composed on a 1280x720 canvas. Brand: navy + orange. */

const HEAD = '"Schibsted Grotesk", system-ui, sans-serif';
const BODY = '"IBM Plex Sans", system-ui, sans-serif';
const MONO = '"IBM Plex Mono", ui-monospace, monospace';

const C = {
  navy: '#0b2545',
  navyDeep: '#07182f',
  navySoft: '#12305a',
  orange: '#fa8e08',
  orangeBright: '#ffa83a',
  green: '#3ddc84',
  red: '#ff6b6b',
  white: '#ffffff',
  mute: 'rgba(255,255,255,0.58)',
  faint: 'rgba(255,255,255,0.32)',
};

/* ---------- shared backdrop (constant across scenes for continuity) ---------- */
function VideoBG() {
  const t = useTime();
  // very slow drift on the glow for "always in motion"
  const gx = 60 + Math.sin(t * 0.18) * 8;
  const gy = -10 + Math.cos(t * 0.15) * 6;
  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden',
      background: `radial-gradient(900px 560px at ${gx}% ${gy}%, rgba(250,142,8,0.18), transparent 58%), linear-gradient(180deg, ${C.navy} 0%, ${C.navyDeep} 100%)` }}>
      {/* faint grid */}
      <div style={{ position: 'absolute', inset: 0,
        backgroundImage: 'linear-gradient(rgba(255,255,255,0.035) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.035) 1px, transparent 1px)',
        backgroundSize: '60px 60px',
        maskImage: 'radial-gradient(900px 560px at 70% 20%, #000, transparent 80%)',
        WebkitMaskImage: 'radial-gradient(900px 560px at 70% 20%, #000, transparent 80%)' }} />
    </div>
  );
}

/* ---------- logo mark (orange rounded square + white hex) ---------- */
function LogoMark({ size = 64, x, y, scale = 1, opacity = 1 }) {
  return (
    <div style={{ position: 'absolute', left: x, top: y, width: size, height: size,
      transform: `scale(${scale})`, transformOrigin: 'center', opacity,
      borderRadius: size * 0.26, background: `linear-gradient(150deg, ${C.orangeBright}, ${C.orange})`,
      display: 'grid', placeItems: 'center', boxShadow: '0 14px 34px rgba(250,142,8,0.40)' }}>
      <img src="../assets/embarc-hex-white.png" alt="" style={{ width: size * 0.6, height: size * 0.6, objectFit: 'contain' }} />
    </div>
  );
}

/* ---------- eyebrow label ---------- */
function Eyebrow({ children, color = C.orangeBright }) {
  return (
    <div style={{ fontFamily: MONO, fontSize: 17, letterSpacing: '0.32em', textTransform: 'uppercase',
      color, display: 'flex', alignItems: 'center', gap: 12 }}>
      <span style={{ width: 26, height: 2, background: color, display: 'inline-block' }} />
      {children}
    </div>
  );
}

/* ---------- progressive line chart (clip-reveal) ---------- */
function LineChart({ points, progress, color, fill, w = 560, h = 250, glowDot = true }) {
  const poly = points.map(p => `${p[0]},${p[1]}`).join(' ');
  const area = `0,${h} ` + poly + ` ${w},${h}`;
  const revealW = w * progress;
  // dot at current end
  const idx = clamp(progress, 0, 1) * (points.length - 1);
  const i0 = Math.floor(idx), i1 = Math.min(points.length - 1, i0 + 1);
  const f = idx - i0;
  const dotX = points[i0][0] + (points[i1][0] - points[i0][0]) * f;
  const dotY = points[i0][1] + (points[i1][1] - points[i0][1]) * f;
  const cid = 'clip' + color.replace(/[^a-z0-9]/gi, '');
  return (
    <svg width={w} height={h} style={{ overflow: 'visible' }}>
      <defs>
        <clipPath id={cid}><rect x="0" y="-40" width={revealW} height={h + 60} /></clipPath>
        <linearGradient id={cid + 'g'} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={fill} stopOpacity="0.42" />
          <stop offset="100%" stopColor={fill} stopOpacity="0" />
        </linearGradient>
      </defs>
      {/* baseline */}
      <line x1="0" y1={h} x2={w} y2={h} stroke="rgba(255,255,255,0.14)" strokeWidth="1.5" />
      <g clipPath={`url(#${cid})`}>
        <polygon points={area} fill={`url(#${cid + 'g'})`} />
        <polyline points={poly} fill="none" stroke={color} strokeWidth="4.5" strokeLinejoin="round" strokeLinecap="round" />
      </g>
      {glowDot && progress > 0.02 && progress < 0.999 && (
        <g>
          <circle cx={dotX} cy={dotY} r="11" fill={color} opacity="0.22" />
          <circle cx={dotX} cy={dotY} r="5.5" fill={color} />
        </g>
      )}
    </svg>
  );
}

/* ---------- pill stat (for problem flicker) ---------- */
function MiniStat({ label, value, danger, delay, x, y }) {
  const { localTime } = useSprite();
  const a = clamp((localTime - delay) / 0.4, 0, 1);
  const ease = Easing.easeOutBack(a);
  return (
    <div style={{ position: 'absolute', left: x, top: y, opacity: a,
      transform: `translateY(${(1 - ease) * 14}px)`,
      display: 'flex', alignItems: 'center', gap: 10,
      background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.10)',
      borderRadius: 12, padding: '12px 16px', backdropFilter: 'blur(4px)' }}>
      <span style={{ fontFamily: MONO, fontSize: 14, letterSpacing: '0.06em', textTransform: 'uppercase', color: C.mute }}>{label}</span>
      <span style={{ fontFamily: HEAD, fontSize: 24, fontWeight: 700, color: danger ? C.red : C.white }}>{value}</span>
    </div>
  );
}

/* =========================================================================
   SCENE 1 — THE PROBLEM (0 – 4.4s)
   ========================================================================= */
function SceneProblem() {
  const { localTime, progress } = useSprite();
  // declining line
  const pts = [[0,70],[95,86],[190,104],[285,128],[380,150],[475,176],[560,206]];
  const draw = animate({ from: 0, to: 1, start: 0.3, end: 1.8, ease: Easing.easeInOutCubic })(localTime);
  const headA = clamp((localTime - 0.15) / 0.5, 0, 1);
  return (
    <div style={{ position: 'absolute', inset: 0 }}>
      <div style={{ position: 'absolute', left: 100, top: 150 }}><Eyebrow color={C.red}>The starting point</Eyebrow></div>
      <div style={{ position: 'absolute', left: 100, top: 196, width: 600, opacity: headA,
        transform: `translateY(${(1 - Easing.easeOutCubic(headA)) * 18}px)`,
        fontFamily: HEAD, fontSize: 62, fontWeight: 700, lineHeight: 1.04, color: C.white, letterSpacing: '-0.02em' }}>
        Stalled.<br />Bleeding spend.<br /><span style={{ color: C.faint }}>Written off.</span>
      </div>
      {/* chart on right */}
      <div style={{ position: 'absolute', left: 700, top: 230 }}>
        <LineChart points={pts} progress={draw} color={C.red} fill={C.red} glowDot={false} />
      </div>
      <MiniStat label="Sales" value="▼ 18%" danger delay={1.6} x={700} y={170} />
      <MiniStat label="ACoS" value="28.4%" danger delay={1.9} x={895} y={170} />
      <MiniStat label="Buy Box" value="61%" danger delay={2.2} x={700} y={500} />
      <MiniStat label="Health" value="At risk" danger delay={2.5} x={905} y={500} />
    </div>
  );
}

/* =========================================================================
   SCENE 2 — ENTER EMBARC (4.4 – 7.8s)
   ========================================================================= */
function SceneEnter() {
  const { localTime } = useSprite();
  const logoS = animate({ from: 0.3, to: 1, start: 0.1, end: 0.9, ease: Easing.easeOutBack })(localTime);
  const logoO = clamp(localTime / 0.5, 0, 1);
  const nameA = clamp((localTime - 0.6) / 0.5, 0, 1);
  const tagA = clamp((localTime - 1.0) / 0.6, 0, 1);
  const tags = ['10 years experience', 'Private label only', 'SPN registered'];
  return (
    <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center' }}>
      <div style={{ position: 'relative', width: 760, textAlign: 'center' }}>
        <div style={{ position: 'relative', height: 110, marginBottom: 10 }}>
          <LogoMark size={96} x={760/2 - 48} y={0} scale={logoS} opacity={logoO} />
        </div>
        <div style={{ opacity: nameA, transform: `translateY(${(1 - Easing.easeOutCubic(nameA)) * 14}px)`,
          fontFamily: HEAD, fontSize: 58, fontWeight: 700, color: C.white, letterSpacing: '-0.02em' }}>
          Then Embarc steps in.
        </div>
        <div style={{ marginTop: 26, display: 'flex', justifyContent: 'center', gap: 14 }}>
          {tags.map((tg, i) => {
            const a = clamp((localTime - 1.0 - i * 0.18) / 0.5, 0, 1);
            return (
              <div key={i} style={{ opacity: a, transform: `translateY(${(1 - Easing.easeOutBack(a)) * 12}px)`,
                fontFamily: MONO, fontSize: 16, letterSpacing: '0.05em', color: C.orangeBright,
                border: `1px solid rgba(250,142,8,0.4)`, background: 'rgba(250,142,8,0.10)',
                borderRadius: 100, padding: '10px 18px' }}>{tg}</div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* =========================================================================
   SCENE 3 — THE PROCESS (7.8 – 16.6s)
   ========================================================================= */
const STEPS = [
  { n: '01', t: 'Audit', s: 'Find what everyone else missed' },
  { n: '02', t: 'Stabilize', s: 'Fix account health & risk' },
  { n: '03', t: 'Optimize', s: 'Listings & SEO that convert' },
  { n: '04', t: 'Advertise', s: 'PPC rebuilt for profit' },
  { n: '05', t: 'Scale', s: 'Launch & grow with momentum' },
];
function SceneProcess() {
  const { localTime } = useSprite();
  const headA = clamp(localTime / 0.5, 0, 1);
  const colW = 210, gap = 18;
  const totalW = STEPS.length * colW + (STEPS.length - 1) * gap;
  const startX = (1280 - totalW) / 2;
  const cardY = 300;
  // connecting progress line
  const lineStart = 1.0, lineEnd = 7.4;
  const lineP = clamp((localTime - lineStart) / (lineEnd - lineStart), 0, 1);
  return (
    <div style={{ position: 'absolute', inset: 0 }}>
      <div style={{ position: 'absolute', left: 0, right: 0, top: 150, display: 'flex', justifyContent: 'center',
        opacity: headA, transform: `translateY(${(1 - Easing.easeOutCubic(headA)) * 14}px)` }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ display: 'flex', justifyContent: 'center' }}><Eyebrow>The process</Eyebrow></div>
          <div style={{ marginTop: 16, fontFamily: HEAD, fontSize: 52, fontWeight: 700, color: C.white, letterSpacing: '-0.02em' }}>
            A decade of judgment, applied in order.
          </div>
        </div>
      </div>
      {/* connecting line behind cards */}
      <div style={{ position: 'absolute', left: startX + 30, top: cardY + 150, width: totalW - 60, height: 3,
        background: 'rgba(255,255,255,0.12)', borderRadius: 2 }}>
        <div style={{ position: 'absolute', left: 0, top: 0, height: '100%', width: `${lineP * 100}%`,
          background: `linear-gradient(90deg, ${C.orange}, ${C.orangeBright})`, borderRadius: 2 }} />
      </div>
      {STEPS.map((st, i) => {
        const appear = 0.7 + i * 1.25;
        const a = clamp((localTime - appear) / 0.55, 0, 1);
        const ease = Easing.easeOutBack(a);
        const active = localTime >= appear && localTime < appear + 1.6;
        return (
          <div key={i} style={{ position: 'absolute', left: startX + i * (colW + gap), top: cardY,
            width: colW, opacity: a, transform: `translateY(${(1 - ease) * 26}px) scale(${0.96 + 0.04 * Math.min(1, ease)})`,
            transformOrigin: 'center bottom' }}>
            <div style={{ height: 196, borderRadius: 18, padding: '22px 20px',
              background: active ? 'linear-gradient(180deg, rgba(250,142,8,0.16), rgba(250,142,8,0.05))' : 'rgba(255,255,255,0.045)',
              border: `1px solid ${active ? 'rgba(250,142,8,0.45)' : 'rgba(255,255,255,0.10)'}`,
              boxShadow: active ? '0 18px 44px rgba(250,142,8,0.18)' : 'none',
              transition: 'background 200ms, border 200ms', display: 'flex', flexDirection: 'column' }}>
              <div style={{ fontFamily: MONO, fontSize: 15, letterSpacing: '0.1em', color: C.orangeBright }}>{st.n}</div>
              <div style={{ marginTop: 14, fontFamily: HEAD, fontSize: 30, fontWeight: 700, color: C.white }}>{st.t}</div>
              <div style={{ marginTop: 10, fontFamily: BODY, fontSize: 16.5, lineHeight: 1.45, color: C.mute }}>{st.s}</div>
            </div>
            {/* node dot on the line */}
            <div style={{ position: 'absolute', left: '50%', top: 150 - cardY + cardY, marginLeft: -7,
              width: 14, height: 14, borderRadius: '50%',
              background: active ? C.orangeBright : 'rgba(255,255,255,0.25)',
              boxShadow: active ? `0 0 0 5px rgba(250,142,8,0.2)` : 'none', display: 'none' }} />
          </div>
        );
      })}
    </div>
  );
}

/* =========================================================================
   SCENE 4 — THE TURNAROUND (16.6 – 21.8s)
   ========================================================================= */
function StatTurn({ label, before, after, fmt, delta, x, y, startAt }) {
  const { localTime } = useSprite();
  const a = clamp((localTime - startAt) / 0.4, 0, 1);
  const val = interpolate([startAt + 0.5, startAt + 2.1], [before, after], Easing.easeOutCubic)(localTime);
  const deltaA = clamp((localTime - startAt - 2.0) / 0.4, 0, 1);
  return (
    <div style={{ position: 'absolute', left: x, top: y, opacity: a,
      transform: `translateY(${(1 - Easing.easeOutCubic(a)) * 18}px)` }}>
      <div style={{ fontFamily: MONO, fontSize: 15, letterSpacing: '0.1em', textTransform: 'uppercase', color: C.mute }}>{label}</div>
      <div style={{ marginTop: 8, display: 'flex', alignItems: 'baseline', gap: 12 }}>
        <span style={{ fontFamily: HEAD, fontSize: 22, fontWeight: 600, color: C.faint, textDecoration: 'line-through' }}>{fmt(before)}</span>
        <span style={{ color: C.faint, fontSize: 20 }}>→</span>
        <span style={{ fontFamily: HEAD, fontSize: 46, fontWeight: 700, color: C.white, letterSpacing: '-0.02em' }}>{fmt(val)}</span>
      </div>
      <div style={{ marginTop: 6, opacity: deltaA, fontFamily: MONO, fontSize: 16, fontWeight: 600, color: C.green }}>{delta}</div>
    </div>
  );
}
function SceneTurn() {
  const { localTime } = useSprite();
  const headA = clamp(localTime / 0.5, 0, 1);
  const pts = [[0,210],[95,206],[190,196],[285,170],[380,128],[475,74],[560,20]];
  const draw = animate({ from: 0, to: 1, start: 0.6, end: 2.6, ease: Easing.easeInOutCubic })(localTime);
  return (
    <div style={{ position: 'absolute', inset: 0 }}>
      <div style={{ position: 'absolute', left: 100, top: 120 }}><Eyebrow>The turnaround</Eyebrow></div>
      <div style={{ position: 'absolute', left: 100, top: 162, width: 600, opacity: headA,
        transform: `translateY(${(1 - Easing.easeOutCubic(headA)) * 16}px)`,
        fontFamily: HEAD, fontSize: 50, fontWeight: 700, lineHeight: 1.05, color: C.white, letterSpacing: '-0.02em' }}>
        The same account &mdash;<br />now scaling.
      </div>
      <StatTurn label="Monthly revenue" before={38} after={127} fmt={v => `$${Math.round(v)}K`} delta="▲ 234%" x={100} y={340} startAt={0.8} />
      <StatTurn label="TACoS" before={28.4} after={11.2} fmt={v => `${v.toFixed(1)}%`} delta="▼ 17.2 pts" x={100} y={470} startAt={1.1} />
      <StatTurn label="Buy Box" before={61} after={98} fmt={v => `${Math.round(v)}%`} delta="▲ 37 pts" x={380} y={470} startAt={1.4} />
      {/* growth chart on right */}
      <div style={{ position: 'absolute', left: 700, top: 250 }}>
        <LineChart points={pts} progress={draw} color={C.orangeBright} fill={C.orange} />
      </div>
      <div style={{ position: 'absolute', left: 705, top: 530, fontFamily: MONO, fontSize: 13, letterSpacing: '0.06em',
        color: C.faint, opacity: clamp((localTime - 1.5) / 0.6, 0, 1) }}>Illustrative example — not a specific client</div>
    </div>
  );
}

/* =========================================================================
   SCENE 5 — CLOSE / CTA (21.8 – 25s)
   ========================================================================= */
function SceneClose() {
  const { localTime, duration } = useSprite();
  const logoS = animate({ from: 0.5, to: 1, start: 0.05, end: 0.7, ease: Easing.easeOutBack })(localTime);
  const a = clamp((localTime - 0.4) / 0.5, 0, 1);
  const ctaA = clamp((localTime - 0.9) / 0.5, 0, 1);
  // gentle fade out at very end for clean loop
  const outA = 1 - clamp((localTime - (duration - 0.5)) / 0.5, 0, 1);
  return (
    <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', opacity: outA }}>
      <div style={{ position: 'relative', width: 820, textAlign: 'center' }}>
        <div style={{ position: 'relative', height: 96, marginBottom: 18 }}>
          <LogoMark size={84} x={820/2 - 42} y={0} scale={logoS} opacity={clamp(localTime/0.4,0,1)} />
        </div>
        <div style={{ opacity: a, transform: `translateY(${(1 - Easing.easeOutCubic(a)) * 14}px)`,
          fontFamily: HEAD, fontSize: 50, fontWeight: 700, color: C.white, letterSpacing: '-0.02em' }}>
          We grow the brands<br />everyone else gave up on.
        </div>
        <div style={{ marginTop: 30, opacity: ctaA, transform: `scale(${0.92 + 0.08 * Easing.easeOutBack(ctaA)})`,
          display: 'inline-flex', alignItems: 'center', gap: 12,
          fontFamily: BODY, fontSize: 22, fontWeight: 600, color: C.navyDeep,
          background: `linear-gradient(150deg, ${C.orangeBright}, ${C.orange})`,
          borderRadius: 100, padding: '16px 34px', boxShadow: '0 18px 40px rgba(250,142,8,0.34)' }}>
          Book a free audit <span style={{ fontSize: 24 }}>→</span>
        </div>
        <div style={{ marginTop: 22, opacity: ctaA, fontFamily: MONO, fontSize: 16, letterSpacing: '0.14em',
          textTransform: 'uppercase', color: C.mute }}>embarcconsulting.com</div>
      </div>
    </div>
  );
}

/* =========================================================================
   ROOT
   ========================================================================= */
function EmbarcVideo() {
  const t = useTime();
  React.useEffect(() => {
    const root = document.getElementById('vroot');
    if (root) root.setAttribute('data-screen-label', `t=${t.toFixed(0)}s`);
  }, [Math.floor(t)]);
  return (
    <div id="vroot" style={{ position: 'absolute', inset: 0 }}>
      <VideoBG />
      <Sprite start={0.0} end={4.4}><SceneProblem /></Sprite>
      <Sprite start={4.4} end={7.8}><SceneEnter /></Sprite>
      <Sprite start={7.8} end={16.6}><SceneProcess /></Sprite>
      <Sprite start={16.6} end={21.8}><SceneTurn /></Sprite>
      <Sprite start={21.8} end={25.0}><SceneClose /></Sprite>
    </div>
  );
}

Object.assign(window, { EmbarcVideo });
