// ───────── Stampa · 40s demo video scenes ─────────
// 1280×720, 40s, 7 scenes.
//   0.0 – 3.5  · Cold open (stamp slams)
//   3.5 – 9.0  · Recording in field
//   9.0 – 16.0 · AI analyzes
//  16.0 – 24.0 · Auto pricing
//  24.0 – 30.5 · WhatsApp send
//  30.5 – 35.5 · Client signs
//  35.5 – 40.0 · Push notification

const { Sprite, useSprite, useTime, useTimeline,
        TextSprite, RectSprite, animate, interpolate, Easing, clamp } = window;

// ════════════════════════════════════════════════════════════════════
// Re-usable bits
// ════════════════════════════════════════════════════════════════════

// Ambient: paper texture + soft warm glow (static)
function Ambient() {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      backgroundImage: `
        radial-gradient(circle at 78% 30%, var(--stamp-glow) 0%, transparent 50%),
        radial-gradient(circle at 18% 75%, rgba(194,131,33,0.12) 0%, transparent 50%),
        radial-gradient(circle, rgba(26,20,14,0.05) 0.8px, transparent 1px)
      `,
      backgroundSize: '100% 100%, 100% 100%, 22px 22px',
    }} />
  );
}

// Phone shell - pass children to fill the screen
function PhoneShell({ x = 200, y = 40, w = 320, h = 640, children, slideIn }) {
  // slideIn: { from, to } in seconds, slides from x = -400 to target x
  let tx = 0, opacity = 1, scale = 1;
  if (slideIn) {
    const t = useTime();
    const ease = animate({ from: 0, to: 1, start: slideIn.from, end: slideIn.to, ease: Easing.easeOutCubic });
    const e = ease(t);
    tx = (1 - e) * -340;
    opacity = e;
    scale = 0.95 + 0.05 * e;
  }
  return (
    <div style={{
      position: 'absolute', left: x, top: y, width: w, height: h,
      background: 'linear-gradient(180deg, #2a2218, #0d0a07)',
      borderRadius: 42, padding: 8,
      boxShadow: '0 40px 80px -20px rgba(26,20,14,0.55), 0 0 0 1px rgba(0,0,0,0.2), inset 0 1px 0 rgba(255,255,255,0.06)',
      transform: `translateX(${tx}px) scale(${scale})`, opacity,
    }}>
      <div style={{
        position: 'absolute', inset: 8,
        background: 'var(--paper)', borderRadius: 34, overflow: 'hidden',
        direction: 'rtl', fontFamily: 'var(--font-sans)', color: 'var(--ink)',
      }}>
        {/* Notch */}
        <div style={{
          position: 'absolute', top: 8, left: '50%', transform: 'translateX(-50%)',
          width: 92, height: 24, background: '#0a0a0a', borderRadius: 14, zIndex: 30,
        }} />
        {/* Status bar */}
        <div style={{
          position: 'absolute', top: 6, left: 0, right: 0, height: 28,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '0 24px', fontFamily: 'var(--font-mono)', fontSize: 11,
          color: 'var(--ink)', zIndex: 20,
        }}>
          <span>9:41</span>
          <span style={{ display: 'flex', gap: 4 }}>
            <span>●●●</span>
            <span>􀙇</span>
          </span>
        </div>
        {children}
      </div>
    </div>
  );
}

// Chyron - bottom-left scene counter + caption
function Chyron({ num, total = 7, label, when }) {
  const { localTime, duration, progress } = useSprite();
  const slideIn = animate({ from: 0, to: 1, start: 0, end: 0.4, ease: Easing.easeOutCubic })(localTime);
  const slideOut = animate({ from: 0, to: 1, start: duration - 0.4, end: duration, ease: Easing.easeInCubic })(localTime);
  const op = slideIn * (1 - slideOut);
  const ty = (1 - slideIn) * 18 + slideOut * -10;

  return (
    <div style={{
      position: 'absolute', bottom: 26, right: 36,
      display: 'flex', alignItems: 'center', gap: 14,
      opacity: op, transform: `translateY(${ty}px)`,
      direction: 'rtl', fontFamily: 'var(--font-sans)', color: 'var(--ink)',
    }}>
      <span className="font-display" style={{ fontSize: 22, letterSpacing: '-0.01em', color: 'var(--ink)' }}>
        {label}
      </span>
      {when && (
        <span style={{
          fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-faint)',
          marginInlineStart: 4, letterSpacing: '0.08em',
        }}>{when}</span>
      )}
    </div>
  );
}

// Stampa seal - circular ring with monogram, optional pulse
function Seal({ size = 96, rotation = -6, glyph = 'ס', color = 'var(--stamp)', opacity = 1 }) {
  const stroke = Math.max(2, size * 0.022);
  return (
    <div style={{
      width: size, height: size, position: 'relative',
      border: `${stroke}px solid currentColor`,
      borderRadius: '999px', color,
      transform: `rotate(${rotation}deg)`,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      opacity,
    }}>
      <div style={{
        position: 'absolute', inset: stroke * 1.6,
        border: `${Math.max(1, stroke * 0.55)}px solid currentColor`,
        borderRadius: '999px', opacity: 0.5,
      }} />
      <span style={{
        fontFamily: 'var(--font-display)', fontSize: size * 0.5,
        fontWeight: 600, lineHeight: 1, marginTop: -size * 0.02,
      }}>{glyph}</span>
      <span style={{
        position: 'absolute', top: stroke * 1.6, left: '50%', transform: 'translateX(-50%)',
        fontSize: size * 0.1, opacity: 0.6,
      }}>★</span>
      <span style={{
        position: 'absolute', bottom: stroke * 1.6, left: '50%', transform: 'translateX(-50%)',
        fontSize: size * 0.1, opacity: 0.6,
      }}>★</span>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════
// SCENE 1 · COLD OPEN  (0 → 3.5)
// ════════════════════════════════════════════════════════════════════
function Scene1ColdOpen() {
  return (
    <Sprite start={0} end={3.6}>
      {({ localTime: t }) => {
        // Stamp slams: scale 4 → 1 in 0.35s with rotation slam
        const stampE = Easing.easeOutBack(clamp(t / 0.35, 0, 1));
        const stampScale = 4 - 3 * stampE;
        const stampRot = -28 + 22 * stampE;
        const stampOp = clamp(t / 0.25, 0, 1);

        // Ripple ring expands after slam
        const rippleT = clamp((t - 0.35) / 0.9, 0, 1);
        const rippleScale = 1 + rippleT * 3.5;
        const rippleOp = (1 - rippleT) * 0.7;

        // Wordmark slides up
        const wordE = animate({ from: 0, to: 1, start: 0.55, end: 1.0, ease: Easing.easeOutCubic })(t);
        const tagE  = animate({ from: 0, to: 1, start: 1.4, end: 1.8, ease: Easing.easeOutCubic })(t);

        // Exit: everything fades in last 0.4s
        const exit = animate({ from: 0, to: 1, start: 3.1, end: 3.5, ease: Easing.easeInCubic })(t);
        const wrapOp = 1 - exit;
        const wrapScale = 1 - exit * 0.1;

        return (
          <div style={{
            position: 'absolute', inset: 0,
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
            opacity: wrapOp, transform: `scale(${wrapScale})`,
          }}>
            {/* Ripple */}
            <div style={{
              position: 'absolute', top: '38%', left: '50%',
              transform: `translate(-50%, -50%) scale(${rippleScale})`,
              width: 240, height: 240, borderRadius: '50%',
              border: '3px solid var(--stamp)', opacity: rippleOp,
            }} />
            <div style={{
              position: 'absolute', top: '38%', left: '50%',
              transform: `translate(-50%, -50%) scale(${rippleScale * 0.7})`,
              width: 240, height: 240, borderRadius: '50%',
              border: '2px solid var(--amber)', opacity: rippleOp * 0.5,
            }} />

            {/* Stamp */}
            <div style={{
              transform: `scale(${stampScale}) rotate(${stampRot}deg)`,
              opacity: stampOp,
              filter: t < 0.4 ? 'blur(2px)' : 'none',
              marginBottom: 32,
            }}>
              <Seal size={220} rotation={0} />
            </div>

            {/* Wordmark */}
            <div style={{
              opacity: wordE, transform: `translateY(${(1 - wordE) * 14}px)`,
              fontFamily: 'var(--font-display)', fontSize: 92, fontWeight: 600,
              color: 'var(--ink)', letterSpacing: '-0.025em', lineHeight: 1,
              direction: 'rtl',
            }}>
              סטמפה
            </div>
            <div style={{
              opacity: tagE, transform: `translateY(${(1 - tagE) * 10}px)`,
              fontFamily: 'var(--font-display)', fontSize: 28, color: 'var(--ink-soft)',
              marginTop: 16, fontStyle: 'italic', direction: 'rtl',
            }}>
              מהקלטה <span style={{ color: 'var(--stamp)' }}>להצעת מחיר חתומה</span>
              <br />
              <span style={{ fontSize: '0.72em', color: 'var(--ink-muted)' }}>- בכמה דקות</span>
            </div>

          </div>
        );
      }}
    </Sprite>
  );
}

// ════════════════════════════════════════════════════════════════════
// SCENE 2 · RECORDING  (3.5 → 9)
// ════════════════════════════════════════════════════════════════════
function Scene2Recording() {
  // Realistic recorder - matches AudioRecorder.tsx: big circular mic button
  // (now showing as "recording" state), pulsing red dot + uppercase מקליט,
  // huge mono timer, 22-bar live level meter (LTR), red stop pill.
  const FULL_TRANSCRIPT = 'במטבח להוריד את הריצוף הקיים, להחליף לפורצלן 60 על 60. סלון אותו ריצוף, בערך 32 מטר. צביעת קירות לבן מט.';
  const METER_BARS = 22;

  return (
    <Sprite start={3.5} end={9.2}>
      {({ localTime: t, duration }) => {
        const charsToShow = Math.floor(clamp(t / 4.5, 0, 1) * FULL_TRANSCRIPT.length);
        const text = FULL_TRANSCRIPT.slice(0, charsToShow);

        const elapsed = Math.min(180, Math.floor(t * 35));
        const mm = String(Math.floor(elapsed / 60)).padStart(2, '0');
        const ss = String(elapsed % 60).padStart(2, '0');

        const sideOp = animate({ from: 0, to: 1, start: 1.0, end: 1.5, ease: Easing.easeOutCubic })(t);
        const sideTx = (1 - sideOp) * 30;
        const exit = animate({ from: 0, to: 1, start: duration - 0.4, end: duration, ease: Easing.easeInCubic })(t);

        // Pulsing red dot: opacity oscillates 1 ↔ 0.35
        const dotPulse = 0.35 + (0.5 + Math.sin(t * 5.2) * 0.5) * 0.65;

        return (
          <div style={{ position: 'absolute', inset: 0, opacity: 1 - exit }}>
            <PhoneShell x={140} y={20} w={360} h={680} slideIn={{ from: 0, to: 0.7 }}>
              <div style={{ position: 'absolute', inset: 0, paddingTop: 44, display: 'flex', flexDirection: 'column' }}>
                {/* App top bar - sticky, matches real app */}
                <div style={{
                  padding: '10px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  borderBottom: '1px solid var(--rule)',
                }}>
                  <span style={{ fontSize: 18, color: 'var(--ink-muted)' }}>×</span>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                    <Seal size={20} />
                    <span className="font-display" style={{ fontSize: 17, fontWeight: 600 }}>סטמפה</span>
                  </div>
                  <span style={{ width: 18 }} />
                </div>

                {/* Real recorder "panel": min-height tall, centered content */}
                <div style={{
                  flex: 1,
                  display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                  padding: '20px 18px', textAlign: 'center', position: 'relative',
                }}>
                  {/* Pulsing red dot + uppercase מקליט */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
                    <span style={{
                      width: 10, height: 10, borderRadius: 999, background: 'var(--rust)',
                      opacity: dotPulse,
                    }} />
                    <span style={{
                      fontSize: 11, fontWeight: 500, color: 'var(--ink-muted)',
                      textTransform: 'uppercase', letterSpacing: '0.18em',
                    }}>
                      מקליט
                    </span>
                  </div>

                  {/* Big mono timer */}
                  <div className="font-mono" style={{
                    fontSize: 52, fontWeight: 600, lineHeight: 1,
                    fontVariantNumeric: 'tabular-nums',
                    color: 'var(--ink)', letterSpacing: '-0.02em',
                    marginBottom: 22,
                  }}>
                    {mm}:{ss}
                  </div>

                  {/* Live level meter - 22 bars, LTR */}
                  <div dir="ltr" style={{
                    width: '100%', maxWidth: 240, height: 64,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    gap: 3, marginBottom: 12, padding: '0 8px',
                  }}>
                    {Array.from({ length: METER_BARS }).map((_, i) => {
                      // Simulate live RMS: most bars quiet, last few active (newest sample on right)
                      const recency = (METER_BARS - 1 - i) / METER_BARS; // 0 = old, 1 = newest
                      const baseEnergy = Math.abs(Math.sin(t * 4 + i * 0.7)) * 0.5;
                      const peak = Math.abs(Math.sin(t * 11 + i * 0.3)) * 0.6 * (1 - recency * 0.6);
                      const lv = clamp(baseEnergy + peak, 0, 1);
                      const active = lv > 0.06;
                      const h = Math.max(6, Math.round(lv * 100));
                      return (
                        <span key={i} style={{
                          display: 'inline-block', width: 4,
                          height: `${h}%`, minHeight: 6,
                          borderRadius: 999,
                          background: active ? 'var(--stamp)' : 'var(--rule)',
                          opacity: active ? 0.9 : 0.6,
                        }} />
                      );
                    })}
                  </div>

                  <div style={{ fontSize: 11, color: 'var(--ink-muted)', minHeight: 16, marginBottom: 18 }}>
                    המיקרופון פעיל - דבר בקול ברור
                  </div>

                  {/* Red stop pill - "סיים והכן הצעה" */}
                  <button style={{
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                    height: 44, padding: '0 22px',
                    borderRadius: 999, border: 0, cursor: 'pointer',
                    background: 'var(--rust)', color: '#fff',
                    fontSize: 13, fontWeight: 500, fontFamily: 'inherit',
                  }}>
                    {/* Square fill icon */}
                    <span style={{ width: 11, height: 11, background: '#fff', borderRadius: 1 }} />
                    סיים והכן הצעה
                  </button>

                  {/* Live transcript card - small, below */}
                  <div style={{
                    marginTop: 18, width: '100%',
                    padding: '10px 12px',
                    background: 'var(--paper-2)', borderRadius: 8,
                    fontSize: 11.5, lineHeight: 1.5, color: 'var(--ink-soft)',
                    textAlign: 'right', minHeight: 72,
                    border: '1px solid var(--rule)',
                  }}>
                    <div style={{
                      fontSize: 9, fontWeight: 600,
                      color: 'var(--ink-muted)', textTransform: 'uppercase',
                      letterSpacing: '0.14em', marginBottom: 5,
                    }}>תמלול חי</div>
                    {text}
                    <span style={{
                      display: 'inline-block', width: 2, height: 12, background: 'var(--stamp)',
                      verticalAlign: 'middle', marginInlineStart: 2,
                      opacity: Math.floor(t * 2) % 2 ? 1 : 0.2,
                    }} />
                  </div>
                </div>
              </div>
            </PhoneShell>

            {/* Side annotation */}
            <div style={{
              position: 'absolute', left: 600, top: 130,
              opacity: sideOp, transform: `translateX(${sideTx}px)`,
              direction: 'rtl', maxWidth: 560,
            }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 14 }}>
                <span style={{
                  fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--stamp)',
                  letterSpacing: '0.12em',
                }}>STEP 01</span>
                <span style={{ width: 60, height: 1, background: 'var(--rule-strong)' }} />
              </div>
              <h2 className="font-display" style={{
                fontSize: 64, lineHeight: 0.98, letterSpacing: '-0.025em',
                margin: 0, color: 'var(--ink)',
              }}>
                דבר. <br />
                <span style={{ color: 'var(--stamp)', fontStyle: 'italic' }}>סטמפה מקליטה.</span>
              </h2>
              <p style={{
                fontSize: 18, lineHeight: 1.5, color: 'var(--ink-soft)',
                marginTop: 22, maxWidth: 460,
              }}>
                בלי טפסים. בלי הקלדה. דבר חופשי תוך כדי הסיור -
                סלנג, מידות בערך, אמירות חצי משפט. סטמפה מבינה עברית קבלנית טבעית.
              </p>
            </div>

            <Chyron num={1} label="הקלטה בשטח" />
          </div>
        );
      }}
    </Sprite>
  );
}

window.VideoScenes_Part1 = { Ambient, PhoneShell, Chyron, Seal, Scene1ColdOpen, Scene2Recording };
