// video-scenes.jsx — kinetic typography scenes for "Für Branding mit Emotionen"
// Uses engine globals: useTime, Easing, interpolate, animate, clamp.
const { useTime: vUseTime, Easing: E, interpolate: vInterp, animate: vAnim, clamp: vClamp } = window;

const VC = {
  bg: '#1A1A1A', bg2: '#212121',
  accent: '#C0392B', accent2: '#D35400',
  text: '#ECECEC', dim: '#8C8C8C', faint: '#5A5A5A',
};
const DISP = "'Barlow Condensed', sans-serif";
const SEMI = "'Barlow Semi Condensed', sans-serif";
const BODY = "'Barlow', sans-serif";

// ── Scene wrapper: opacity envelope + centered full frame ───────────────────
function SceneWrap({ start, end, fadeIn = 0.5, fadeOut = 0.5, bg, children }) {
  const t = vUseTime();
  if (t < start - 0.0001 || t > end + 0.0001) return null;
  const lt = t - start;
  const dur = end - start;
  let op = 1;
  if (fadeIn > 0 && lt < fadeIn) op = E.easeInOutSine(vClamp(lt / fadeIn, 0, 1));
  else if (fadeOut > 0 && lt > dur - fadeOut) op = E.easeInOutSine(vClamp((dur - lt) / fadeOut, 0, 1));
  return (
    <div style={{ position: 'absolute', inset: 0, opacity: op, background: bg || 'transparent', overflow: 'hidden' }}>
      {children(lt, dur, t)}
    </div>
  );
}

const Kicker = ({ text, color = VC.dim, size = 46, ...rest }) => (
  <div style={{ fontFamily: SEMI, textTransform: 'uppercase', letterSpacing: '0.42em',
    fontSize: size, fontWeight: 600, color, ...rest }}>{text}</div>
);

// ── SCENE 1 — MANCHMAL LAUT. (loud: slam + shake + sound blasts) ────────────
function SceneLaut({ start, end }) {
  return (
    <SceneWrap start={start} end={end} fadeIn={0.04} fadeOut={0.45}
      bg="radial-gradient(120% 100% at 50% 42%, #2a1714 0%, #1A1A1A 60%)">
      {(lt, dur, t) => {
        // entry slam
        const scale = vAnim({ from: 1.6, to: 1, start: 0, end: 0.55, ease: E.easeOutBack })(lt);
        const introOp = vClamp(lt / 0.18, 0, 1);
        // decaying vibration
        const decay = vClamp(1 - (lt - 0.55) / 2.6, 0, 1);
        const shakeX = lt > 0.55 ? Math.sin(t * 58) * 5 * decay : 0;
        const shakeY = lt > 0.55 ? Math.cos(t * 71) * 4 * decay : 0;
        // flash
        const flash = vClamp(1 - lt / 0.3, 0, 1) * 0.55;
        const rings = [0, 1, 2, 3, 4];
        return (
          <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
            alignItems: 'center', justifyContent: 'center' }}>
            {/* sound blast rings */}
            {rings.map((i) => {
              const phase = ((lt * 0.85) + i * 0.26) % 1;
              const d = phase * 1700;
              const o = (1 - phase) * 0.4 * vClamp(lt / 0.4, 0, 1);
              return <div key={i} style={{ position: 'absolute', left: '50%', top: '46%',
                width: d, height: d, marginLeft: -d / 2, marginTop: -d / 2, borderRadius: '50%',
                border: `${3 + (1 - phase) * 5}px solid ${i % 2 ? VC.accent2 : VC.accent}`, opacity: o }} />;
            })}
            <div style={{ transform: `translate(${shakeX}px, ${shakeY - 40}px) scale(${scale})`,
              opacity: introOp, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
              <Kicker text="Manchmal" marginBottom={6} />
              <div style={{ fontFamily: DISP, fontWeight: 700, fontSize: 400, lineHeight: 0.86,
                color: VC.accent, letterSpacing: '0.005em', textShadow: '0 0 60px rgba(192,57,43,0.4)' }}>LAUT.</div>
            </div>
            <div style={{ position: 'absolute', inset: 0, background: '#fff', opacity: flash, mixBlendMode: 'overlay' }} />
          </div>
        );
      }}
    </SceneWrap>
  );
}

// ── SCENE 2 — MANCHMAL LEISE. (quiet: soft blur-in, drift, hush) ────────────
function SceneLeise({ start, end }) {
  return (
    <SceneWrap start={start} end={end} fadeIn={0.7} fadeOut={0.04}
      bg="radial-gradient(120% 100% at 50% 55%, #1d1d1d 0%, #131313 70%)">
      {(lt, dur, t) => {
        const blur = vClamp(10 - lt * 9, 0, 10);
        const drift = -lt * 6; // slow upward drift
        const track = vInterp([0, 1.2], [0.34, 0.5], E.easeOutCubic)(lt);
        const lineW = vAnim({ from: 0, to: 360, start: 0.3, end: 1.6, ease: E.easeOutCubic })(lt);
        return (
          <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
            alignItems: 'center', justifyContent: 'center', transform: `translateY(${drift}px)` }}>
            <Kicker text="Manchmal" color={VC.faint} size={40} marginBottom={26} />
            <div style={{ fontFamily: BODY, fontWeight: 300, fontSize: 230, lineHeight: 1,
              color: VC.text, letterSpacing: `${track}em`, filter: `blur(${blur}px)`, paddingLeft: `${track}em` }}>leise.</div>
            <div style={{ width: lineW, height: 2, background: `linear-gradient(90deg, transparent, ${VC.faint}, transparent)`, marginTop: 40 }} />
          </div>
        );
      }}
    </SceneWrap>
  );
}

// ── SCENE 3 — MANCHMAL KRAFTVOLL. (powerful: drive-in + speed lines) ────────
function SceneKraftvoll({ start, end }) {
  return (
    <SceneWrap start={start} end={end} fadeIn={0.05} fadeOut={0.45}
      bg="linear-gradient(105deg, #1A1A1A 0%, #241310 55%, #1A1A1A 100%)">
      {(lt, dur, t) => {
        const x = vAnim({ from: -620, to: 0, start: 0, end: 0.6, ease: E.easeOutBack })(lt);
        const zoom = vInterp([0.6, dur], [1, 1.04], E.easeOutSine)(lt);
        const op = vClamp(lt / 0.15, 0, 1);
        const lines = [0, 1, 2, 3, 4, 5, 6, 7];
        return (
          <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
            {/* diagonal speed lines */}
            <div style={{ position: 'absolute', inset: '-20%', transform: 'rotate(-14deg)' }}>
              {lines.map((i) => {
                const phase = ((t * 0.55) + i * 0.135) % 1;
                const lx = -400 + phase * 3000;
                const o = Math.sin(phase * Math.PI) * 0.5;
                const len = 180 + (i % 3) * 160;
                return <div key={i} style={{ position: 'absolute', top: `${8 + i * 12}%`, left: lx,
                  width: len, height: i % 2 ? 4 : 6, background: i % 2 ? VC.accent2 : VC.accent,
                  opacity: o, borderRadius: 4 }} />;
              })}
            </div>
            <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center',
              transform: `translateX(${x}px) scale(${zoom})`, opacity: op }}>
              <Kicker text="Manchmal" color={VC.dim} marginBottom={4} />
              <div style={{ fontFamily: DISP, fontWeight: 700, fontSize: 200, lineHeight: 0.86,
                whiteSpace: 'nowrap', letterSpacing: '0.005em',
                background: `linear-gradient(95deg, ${VC.accent2}, ${VC.accent} 70%)`,
                WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent' }}>KRAFTVOLL.</div>
            </div>
          </div>
        );
      }}
    </SceneWrap>
  );
}

// ── SCENE 4 — MANCHMAL RUHIGER. (calm: slow waves, settle) ──────────────────
function CalmWaves({ t }) {
  const W = 1920, H = 1080, mid = 640;
  const mk = (amp, speed, phase, stroke, op, yoff) => {
    let d = `M 0 ${mid + yoff}`;
    for (let x = 0; x <= W; x += 40) {
      const y = mid + yoff + Math.sin((x / W) * Math.PI * 3 + t * speed + phase) * amp;
      d += ` L ${x} ${y}`;
    }
    return <path d={d} fill="none" stroke={stroke} strokeWidth="3" opacity={op} strokeLinecap="round" />;
  };
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
      {mk(34, 0.6, 0, VC.accent, 0.22, 150)}
      {mk(26, 0.8, 1.4, VC.accent2, 0.18, 200)}
      {mk(20, 0.45, 3.1, '#6a8caf', 0.16, 250)}
    </svg>
  );
}
function SceneRuhiger({ start, end }) {
  return (
    <SceneWrap start={start} end={end} fadeIn={0.7} fadeOut={0.5}
      bg="radial-gradient(120% 110% at 50% 38%, #20242a 0%, #161616 72%)">
      {(lt, dur, t) => {
        const track = vInterp([0, 1.5], [0.28, 0.4], E.easeOutCubic)(lt);
        const rise = vAnim({ from: 22, to: 0, start: 0, end: 1.4, ease: E.easeOutCubic })(lt);
        return (
          <div style={{ position: 'absolute', inset: 0 }}>
            <CalmWaves t={t} />
            <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center', transform: `translateY(${-30 + rise}px)` }}>
              <Kicker text="Manchmal" color={VC.faint} size={40} marginBottom={24} />
              <div style={{ fontFamily: BODY, fontWeight: 400, fontSize: 220, lineHeight: 1,
                color: VC.text, letterSpacing: `${track}em`, paddingLeft: `${track}em` }}>ruhiger.</div>
            </div>
          </div>
        );
      }}
    </SceneWrap>
  );
}

// ── Tacho mark (bridge to website) ──────────────────────────────────────────
const polar = (cx, cy, r, deg) => { const a = (deg - 90) * Math.PI / 180; return [cx + r * Math.cos(a), cy + r * Math.sin(a)]; };
function arcPath(cx, cy, r, d0, d1) {
  const [x0, y0] = polar(cx, cy, r, d0), [x1, y1] = polar(cx, cy, r, d1);
  const large = (d1 - d0) > 180 ? 1 : 0;
  return `M ${x0} ${y0} A ${r} ${r} 0 ${large} 1 ${x1} ${y1}`;
}
const tachoAngle = (v) => 225 + (v / 8000) * 270;
function TachoMark({ prog }) {
  const cx = 130, cy = 128, R = 100;
  const ang = 225 + (tachoAngle(7900) - 225) * E.easeOutCubic(prog);
  const ticks = [];
  for (let v = 0; v <= 8000; v += 1000) {
    const deg = tachoAngle(v); const red = v >= 6500;
    const [ox, oy] = polar(cx, cy, R, deg); const [ix, iy] = polar(cx, cy, R - 16, deg);
    ticks.push(<line key={v} x1={ox} y1={oy} x2={ix} y2={iy} stroke={red ? VC.accent : '#cfcfcf'} strokeWidth="3.5" strokeLinecap="round" />);
  }
  return (
    <svg viewBox="0 0 260 175" style={{ width: 300, height: 202 }}>
      <path d={arcPath(cx, cy, R, 225, 495)} fill="none" stroke="#3a3a3a" strokeWidth="6" strokeLinecap="round" />
      <path d={arcPath(cx, cy, R, tachoAngle(6500), 495)} fill="none" stroke={VC.accent} strokeWidth="6" strokeLinecap="round" />
      {ticks}
      <g transform={`rotate(${ang} ${cx} ${cy})`}>
        <polygon points={`${cx - 4},${cy} ${cx + 4},${cy} ${cx + 2},${cy - R + 12} ${cx - 2},${cy - R + 12}`} fill={VC.accent} />
      </g>
      <circle cx={cx} cy={cy} r="13" fill="#111" stroke={VC.accent} strokeWidth="2.5" />
      <circle cx={cx} cy={cy} r="4.5" fill={VC.accent} />
    </svg>
  );
}

// ── SCENE 5 — OUTRO (tagline → brand signature) ─────────────────────────────
function SceneOutro({ start, end }) {
  return (
    <SceneWrap start={start} end={end} fadeIn={0.7} fadeOut={0}
      bg="radial-gradient(130% 120% at 50% 40%, #232323 0%, #161616 72%)">
      {(lt, dur, t) => {
        // Beat A: tagline (0 → 2.7), Beat B: signature (2.6 → end)
        const aOut = vClamp(1 - (lt - 2.4) / 0.5, 0, 1);
        const aIn = vClamp(lt / 0.5, 0, 1);
        const aOp = E.easeInOutSine(Math.min(aIn, aOut));
        const bIn = vClamp((lt - 2.6) / 0.6, 0, 1);
        const bOp = E.easeOutCubic(bIn);
        const bRise = (1 - bOp) * 26;
        const needleProg = vClamp((lt - 2.9) / 1.5, 0, 1);
        return (
          <div style={{ position: 'absolute', inset: 0 }}>
            {/* racing stripe */}
            <div style={{ position: 'absolute', left: 0, top: 0, width: 16, height: '100%',
              background: VC.accent, opacity: bOp }}>
              <div style={{ position: 'absolute', left: 16, top: 0, width: 3, height: '100%', background: VC.accent2, opacity: 0.6 }} />
            </div>

            {/* Beat A — tagline */}
            <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center',
              justifyContent: 'center', opacity: aOp, flexDirection: 'column' }}>
              <div style={{ fontFamily: DISP, fontWeight: 600, fontSize: 112, lineHeight: 1.04,
                color: VC.text, textAlign: 'center', letterSpacing: '0.01em', textTransform: 'uppercase' }}>
                Für Branding<br />mit <span style={{ color: VC.accent }}>Emotionen.</span>
              </div>
            </div>

            {/* Beat B — signature */}
            <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center', opacity: bOp,
              transform: `translateY(${bRise}px)` }}>
              <TachoMark prog={needleProg} />
              <div style={{ fontFamily: DISP, fontWeight: 700, fontSize: 124, lineHeight: 0.92,
                color: VC.text, textTransform: 'uppercase', letterSpacing: '0.01em', marginTop: 18, whiteSpace: 'nowrap' }}>
                Mark Schönholzer
              </div>
              <div style={{ fontFamily: SEMI, fontWeight: 600, fontSize: 36, letterSpacing: '0.34em',
                textTransform: 'uppercase', color: VC.accent, marginTop: 26, whiteSpace: 'nowrap' }}>
                Senior Marketing Leader
              </div>
            </div>
          </div>
        );
      }}
    </SceneWrap>
  );
}

Object.assign(window, { SceneLaut, SceneLeise, SceneKraftvoll, SceneRuhiger, SceneOutro, VC });
