// ───────── Stampa video · Scenes 3, 4, 5 (AI / Pricing / WhatsApp) ─────────

const { Sprite: Sprite2, useSprite: useSprite2, animate: animate2, Easing: Easing2, clamp: clamp2 } = window;
const { Seal: Seal2, PhoneShell: PhoneShell2, Chyron: Chyron2 } = window.VideoScenes_Part1;

// ════════════════════════════════════════════════════════════════════
// SCENE 3 · AI ANALYZES  (9 → 16)
// ════════════════════════════════════════════════════════════════════
// Phone shows transcript with highlighted chunks; chunks "fly" out toward
// the AI hub (right side). Hub has orbiting rings + categories light up.

const CHUNKS = [
  // text, category color var, category label, fly-out time
  { text: 'ריצוף',      c: 'cat-demo',  cat: 'הריסות',    t: 0.6 },
  { text: 'פורצלן 60×60', c: 'cat-floor', cat: 'ריצוף',     t: 1.4 },
  { text: '32 מטר',      c: 'cat-floor', cat: 'ריצוף',     t: 2.2 },
  { text: 'לבן מט',      c: 'cat-paint', cat: 'צבע',        t: 3.0 },
  { text: 'שקעים',       c: 'cat-elec',  cat: 'חשמל',      t: 3.8 },
  { text: 'ברז',         c: 'cat-plumb', cat: 'אינסטלציה', t: 4.6 },
];

function Scene3AI() {
  return (
    <Sprite start={9} end={16.3}>
      {({ localTime: t, duration }) => {
        const exit = animate2({ from: 0, to: 1, start: duration - 0.4, end: duration, ease: Easing2.easeInCubic })(t);
        const op = 1 - exit;

        return (
          <div style={{ position: 'absolute', inset: 0, opacity: op }}>
            {/* Phone with transcript */}
            <PhoneShell2 x={80} y={20} w={360} h={680}>
              <div style={{ position: 'absolute', inset: 0, paddingTop: 50, display: 'flex', flexDirection: 'column' }}>
                <div style={{ padding: '8px 18px' }}>
                  <div className="smallcaps" style={{ fontSize: 9, marginBottom: 3 }}>הצעה #143</div>
                  <div className="font-display" style={{ fontSize: 18 }}>שיפוץ - קרליבך 14</div>
                </div>

                {/* Transcript with progressive highlights */}
                <div style={{
                  margin: '6px 14px',
                  background: 'var(--panel)', border: '1px solid var(--rule)',
                  borderRadius: 12, padding: 14,
                  fontSize: 13, lineHeight: 1.7, color: 'var(--ink-soft)',
                }}>
                  <div className="smallcaps" style={{ fontSize: 9, marginBottom: 8 }}>תמלול</div>
                  <Highlightable t={t} chunks={CHUNKS} />
                </div>

                {/* Thinking strip */}
                <div style={{
                  margin: '10px 14px 0',
                  padding: '10px 12px', borderRadius: 10,
                  background: 'var(--stamp-soft)',
                  display: 'flex', alignItems: 'center', gap: 8,
                  border: '1px solid var(--stamp)',
                }}>
                  <span style={{ display: 'inline-flex', gap: 3 }}>
                    {[0, 0.2, 0.4].map((d, i) => (
                      <span key={i} style={{
                        width: 5, height: 5, borderRadius: 999, background: 'var(--stamp)',
                        opacity: 0.3 + Math.abs(Math.sin(t * 3 + d * 6)) * 0.7,
                      }} />
                    ))}
                  </span>
                  <span style={{ fontSize: 12, color: 'var(--stamp)', fontWeight: 600 }}>
                    סטמפה חושבת...
                  </span>
                  <span style={{
                    marginInlineStart: 'auto', fontFamily: 'var(--font-mono)', fontSize: 10,
                    color: 'var(--stamp-ink)',
                  }}>
                    {Math.min(6, Math.floor((t / 5) * 6))} פריטים
                  </span>
                </div>

                {/* Discovered categories list */}
                <div style={{ padding: '14px 14px 0', flex: 1 }}>
                  <div className="smallcaps" style={{ fontSize: 9, marginBottom: 8 }}>קטגוריות שזוהו</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                    {CHUNKS.map((c, i) => {
                      const visible = t > c.t + 0.8;
                      const e = animate2({ from: 0, to: 1, start: c.t + 0.6, end: c.t + 1.1, ease: Easing2.easeOutBack })(t);
                      return (
                        <div key={i} style={{
                          display: 'flex', alignItems: 'center', gap: 8,
                          padding: '6px 10px', borderRadius: 8,
                          background: 'var(--panel)', border: '1px solid var(--rule)',
                          borderRightWidth: 3, borderRightColor: `var(--${c.c})`,
                          fontSize: 11.5,
                          opacity: e, transform: `translateX(${(1 - e) * 30}px)`,
                        }}>
                          <span className="cat-dot" style={{ background: `var(--${c.c})` }} />
                          <span style={{ fontWeight: 600 }}>{c.cat}</span>
                          <span style={{ color: 'var(--ink-muted)', marginInlineStart: 'auto', fontSize: 10 }}>
                            {c.text}
                          </span>
                          <span style={{
                            fontFamily: 'var(--font-mono)', fontSize: 9,
                            color: 'var(--sage)', border: '1px solid var(--sage)',
                            padding: '0 4px', borderRadius: 3,
                          }}>{90 + i}%</span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>
            </PhoneShell2>

            {/* Flying chunks - leave phone, fly into hub */}
            {CHUNKS.map((c, i) => {
              const flyStart = c.t;
              const flyEnd = c.t + 0.7;
              if (t < flyStart || t > flyEnd + 0.2) return null;
              const e = clamp2((t - flyStart) / (flyEnd - flyStart), 0, 1);
              const ease = Easing2.easeInOutCubic(e);
              // start near transcript (around x=300, y=200+i*20)
              const sx = 300; const sy = 200 + i * 6;
              // end at hub center
              const ex = 870; const ey = 360;
              const x = sx + (ex - sx) * ease;
              const y = sy + (ey - sy) * ease;
              const op = e < 0.5 ? 1 : 1 - (e - 0.5) * 2;
              return (
                <div key={i} style={{
                  position: 'absolute', left: x, top: y,
                  transform: `translate(-50%, -50%) scale(${1 - ease * 0.4})`,
                  padding: '4px 9px', borderRadius: 999,
                  background: `var(--${c.c})`, color: '#fff',
                  fontSize: 11, fontWeight: 600, direction: 'rtl',
                  opacity: op,
                  boxShadow: `0 4px 12px -2px var(--${c.c})`,
                  whiteSpace: 'nowrap',
                  fontFamily: 'var(--font-sans)',
                }}>
                  {c.text}
                </div>
              );
            })}

            {/* AI Hub */}
            <AIHub t={t} />

            {/* Side caption */}
            <div style={{
              position: 'absolute', right: 36, top: 80, direction: 'rtl', maxWidth: 360,
              opacity: animate2({ from: 0, to: 1, start: 0.3, end: 0.9, ease: Easing2.easeOutCubic })(t),
            }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 12 }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--stamp)', letterSpacing: '0.12em' }}>
                  STEP 02
                </span>
                <span style={{ width: 50, height: 1, background: 'var(--rule-strong)' }} />
              </div>
              <h2 className="font-display" style={{
                fontSize: 48, lineHeight: 1, letterSpacing: '-0.02em', margin: 0,
              }}>
                הבינה <span style={{ color: 'var(--stamp)', fontStyle: 'italic' }}>מנתחת.</span>
              </h2>
              <p style={{
                fontSize: 14, lineHeight: 1.5, color: 'var(--ink-soft)', marginTop: 14,
              }}>
                מילים → קטגוריות → כמויות. סלנג קבלני מומר לפריטים סטנדרטיים.
              </p>
            </div>

            <Chyron2 num={2} label="ניתוח חכם" />
          </div>
        );
      }}
    </Sprite>
  );
}

// Highlightable transcript - highlights chunks one at a time as `t` passes their `t`
function Highlightable({ t, chunks }) {
  const FULL = 'במטבח להוריד את הריצוף הקיים, להחליף לפורצלן 60×60. בסלון אותו ריצוף - בערך 32 מטר. צביעת קירות לבן מט. הוספת שקעים והחלפת ברז מטבח.';

  // Find which chunks are "active" (lit), which are "consumed" (faded)
  const parts = [];
  let cursor = 0;
  // Sort chunks by appearance in FULL
  const found = chunks.map((c) => ({ ...c, idx: FULL.indexOf(c.text) })).filter(c => c.idx >= 0).sort((a, b) => a.idx - b.idx);

  found.forEach((c, i) => {
    if (cursor < c.idx) parts.push({ type: 'plain', text: FULL.slice(cursor, c.idx) });
    parts.push({ type: 'chunk', text: c.text, c });
    cursor = c.idx + c.text.length;
  });
  if (cursor < FULL.length) parts.push({ type: 'plain', text: FULL.slice(cursor) });

  return (
    <span>
      {parts.map((p, i) => {
        if (p.type === 'plain') return <span key={i}>{p.text}</span>;
        const c = p.c;
        const lit = t >= c.t - 0.2 && t < c.t + 0.3;
        const consumed = t >= c.t + 0.3;
        const op = consumed ? 0.35 : 1;
        const bg = lit ? `var(--${c.c})` : (consumed ? 'transparent' : 'transparent');
        const color = lit ? '#fff' : (consumed ? 'var(--ink-muted)' : 'var(--ink)');
        const fw = lit ? 600 : (consumed ? 400 : 500);
        return (
          <span key={i} style={{
            background: bg, color, fontWeight: fw,
            padding: lit ? '1px 4px' : 0, borderRadius: 3,
            transition: 'all 200ms',
          }}>{p.text}</span>
        );
      })}
    </span>
  );
}

// AI Hub - orbiting seal with rings
function AIHub({ t }) {
  return (
    <div style={{
      position: 'absolute', left: 800, top: 280,
      width: 140, height: 140,
    }}>
      {/* Outer pulsing ring */}
      <div style={{
        position: 'absolute', inset: -20, borderRadius: '50%',
        border: '1px solid var(--stamp)', opacity: 0.2 + Math.sin(t * 2) * 0.1,
        transform: `scale(${1 + Math.sin(t * 2) * 0.05})`,
      }} />
      {/* Dashed orbit */}
      <div style={{
        position: 'absolute', inset: 0, borderRadius: '50%',
        border: '1.5px dashed var(--rule-strong)',
        animation: 'aiOrbit 8s linear infinite',
      }} />
      {/* Inner solid orbit */}
      <div style={{
        position: 'absolute', inset: 14, borderRadius: '50%',
        border: '1px solid var(--stamp-soft)',
        animation: 'aiOrbit 5s linear infinite reverse',
      }} />

      {/* Orbiting dot 1 */}
      <div style={{
        position: 'absolute', top: -4, left: '50%', marginLeft: -5,
        width: 10, height: 10, borderRadius: 999, background: 'var(--stamp)',
        boxShadow: '0 0 12px var(--stamp)',
        animation: 'aiOrbitWrap 8s linear infinite',
        transformOrigin: '5px 74px',
      }} />
      {/* Orbiting dot 2 */}
      <div style={{
        position: 'absolute', top: 12, left: '50%', marginLeft: -3,
        width: 6, height: 6, borderRadius: 999, background: 'var(--amber)',
        boxShadow: '0 0 8px var(--amber)',
        animation: 'aiOrbitWrap 5s linear infinite reverse',
        transformOrigin: '3px 58px',
      }} />

      {/* Center seal */}
      <div style={{
        position: 'absolute', inset: 24,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        transform: `rotate(${t * 8}deg)`,
      }}>
        <Seal2 size={92} rotation={0} />
      </div>

      <style>{`
        @keyframes aiOrbit { to { transform: rotate(360deg); } }
        @keyframes aiOrbitWrap { to { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════
// SCENE 4 · AUTO PRICING  (16 → 24)
// ════════════════════════════════════════════════════════════════════
const PRICE_ROWS = [
  { c: 'cat-demo',  cat: 'הריסות',  d: 'פירוק ריצוף קיים',   q: 54,  u: 'מ״ר', up: 65,  total: 3510, t: 0.4 },
  { c: 'cat-floor', cat: 'ריצוף',   d: 'פורצלן 60×60',         q: 54,  u: 'מ״ר', up: 145, total: 7830, t: 1.0 },
  { c: 'cat-paint', cat: 'צבע',     d: 'קירות לבן מט',         q: 210, u: 'מ״ר', up: 19,  total: 3990, t: 1.7 },
  { c: 'cat-elec',  cat: 'חשמל',    d: 'הוספת שקעים',          q: 2,   u: 'יח׳', up: 285, total: 570,  t: 2.4 },
  { c: 'cat-plumb', cat: 'אינסט.',  d: 'החלפת ברז מטבח',      q: 1,   u: 'יח׳', up: 420, total: 420,  t: 3.0 },
  { c: 'cat-gyp',   cat: 'גבס',     d: 'תקרת גבס סלון',        q: 24,  u: 'מ״ר', up: 95,  total: 2280, t: 3.6 },
];
const FINAL_TOTAL = PRICE_ROWS.reduce((s, r) => s + r.total, 0); // 18,600

function Scene4Pricing() {
  return (
    <Sprite start={16} end={24.3}>
      {({ localTime: t, duration }) => {
        const exit = animate2({ from: 0, to: 1, start: duration - 0.5, end: duration, ease: Easing2.easeInCubic })(t);
        const op = 1 - exit;

        // Total counter - counts up alongside the rows
        const totalE = animate2({ from: 0, to: 1, start: 1.0, end: 4.5, ease: Easing2.easeOutCubic })(t);
        const subtotal = Math.floor(FINAL_TOTAL * totalE);
        const vat = Math.floor(subtotal * 0.18);
        const grand = subtotal + vat;

        return (
          <div style={{ position: 'absolute', inset: 0, opacity: op }}>
            {/* Phone - realistic BOQ table layout matching BOQTable.tsx */}
            <PhoneShell2 x={80} y={20} w={360} h={680}>
              <div style={{ position: 'absolute', inset: 0, paddingTop: 44, display: 'flex', flexDirection: 'column' }}>
                {/* App top bar */}
                <div style={{
                  padding: '10px 16px',
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  borderBottom: '1px solid var(--rule)',
                }}>
                  <span style={{ fontSize: 16, color: 'var(--ink-muted)' }}>‹</span>
                  <div style={{ textAlign: 'center', lineHeight: 1.2 }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>שיפוץ קרליבך 14</div>
                    <div className="font-mono" style={{ fontSize: 9, color: 'var(--ink-muted)' }}>#143 · גלית מורן</div>
                  </div>
                  <span style={{ fontSize: 13, color: 'var(--ink-muted)' }}>···</span>
                </div>

                {/* Summary panel - matches the app's summary block */}
                <div style={{
                  margin: '10px 12px 6px',
                  padding: '10px 12px',
                  background: 'var(--panel-warm)',
                  border: '1px solid var(--rule-strong)',
                  borderRadius: 8,
                  display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
                }}>
                  <div>
                    <div style={{
                      fontSize: 9, color: 'var(--ink-muted)',
                      textTransform: 'uppercase', letterSpacing: '0.14em', fontWeight: 600,
                      marginBottom: 4,
                    }}>
                      סה״כ · כולל מע״מ
                    </div>
                    <div className="font-mono" style={{
                      fontSize: 26, fontWeight: 700, lineHeight: 1,
                      color: 'var(--stamp)', fontVariantNumeric: 'tabular-nums',
                    }}>
                      ₪ {grand.toLocaleString('he-IL')}
                    </div>
                  </div>
                  <div style={{ textAlign: 'left', lineHeight: 1.5 }}>
                    <div className="font-mono" style={{ fontSize: 9, color: 'var(--ink-muted)' }}>
                      ביניים ₪{subtotal.toLocaleString('he-IL')}
                    </div>
                    <div className="font-mono" style={{ fontSize: 9, color: 'var(--ink-muted)' }}>
                      מע״מ ₪{vat.toLocaleString('he-IL')}
                    </div>
                  </div>
                </div>

                {/* Real BOQ table - category-grouped */}
                <div style={{ flex: 1, padding: '6px 12px 4px', overflow: 'hidden' }}>
                  {(() => {
                    // Group rows by category, preserving the row's reveal time
                    const cats = [];
                    let lastCat = null;
                    PRICE_ROWS.forEach((r) => {
                      if (r.cat !== lastCat) {
                        cats.push({ cat: r.cat, c: r.c, rows: [] });
                        lastCat = r.cat;
                      }
                      cats[cats.length - 1].rows.push(r);
                    });

                    let itemNum = 0;
                    return cats.map((g, gi) => {
                      itemNum++;
                      let subNum = 0;
                      const catTotal = g.rows.reduce((s, r) => s + r.total, 0);
                      const firstRowT = g.rows[0].t;
                      const catE = animate2({ from: 0, to: 1, start: firstRowT, end: firstRowT + 0.3, ease: Easing2.easeOutCubic })(t);
                      if (catE === 0) return null;

                      return (
                        <div key={gi} style={{ opacity: catE }}>
                          {/* Category header strip - dashed underline, paper-2 bg */}
                          <div style={{
                            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                            padding: '5px 8px',
                            background: 'var(--paper-2)',
                            borderBottom: '1px dashed var(--rule)',
                            borderTop: gi > 0 ? '1px solid var(--rule)' : 0,
                          }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                              <span style={{
                                width: 8, height: 8, borderRadius: 999,
                                background: `var(--${g.c})`,
                              }} />
                              <span style={{
                                fontSize: 11, fontWeight: 600, color: 'var(--ink)',
                                letterSpacing: '0.02em',
                              }}>{g.cat}</span>
                              <span className="font-mono" style={{ fontSize: 9, color: 'var(--ink-muted)' }}>
                                {g.rows.length === 1 ? 'פריט' : `${g.rows.length} פריטים`}
                              </span>
                            </div>
                            <span className="font-mono" style={{ fontSize: 10, color: 'var(--ink-muted)' }}>
                              ₪ {catTotal.toLocaleString('he-IL')}
                            </span>
                          </div>

                          {/* Item rows */}
                          {g.rows.map((r, ri) => {
                            subNum++;
                            const rowE = animate2({ from: 0, to: 1, start: r.t, end: r.t + 0.4, ease: Easing2.easeOutCubic })(t);
                            if (rowE === 0) return null;
                            const itemId = `${itemNum}.${subNum}`;
                            return (
                              <div key={ri} style={{
                                display: 'grid', gridTemplateColumns: '1fr auto auto',
                                gap: 8, alignItems: 'center',
                                padding: '6px 8px',
                                borderBottom: '1px solid var(--rule)',
                                opacity: rowE, transform: `translateY(${(1 - rowE) * 6}px)`,
                              }}>
                                <div style={{ display: 'flex', alignItems: 'flex-start', gap: 6, minWidth: 0 }}>
                                  <span className="font-mono" style={{
                                    fontSize: 9, color: 'var(--ink-faint)', paddingTop: 2, flexShrink: 0,
                                  }}>{itemId}</span>
                                  <span style={{
                                    fontSize: 11.5, color: 'var(--ink)', lineHeight: 1.35,
                                    overflow: 'hidden', textOverflow: 'ellipsis',
                                  }}>{r.d}</span>
                                </div>
                                <span className="font-mono" style={{
                                  fontSize: 10, color: 'var(--ink-muted)', whiteSpace: 'nowrap',
                                  fontVariantNumeric: 'tabular-nums',
                                }}>
                                  {r.q}×{r.up}
                                </span>
                                <span className="font-mono" style={{
                                  fontSize: 12, fontWeight: 600, color: 'var(--ink)',
                                  fontVariantNumeric: 'tabular-nums', minWidth: 50, textAlign: 'left',
                                }}>
                                  ₪{r.total.toLocaleString('he-IL')}
                                </span>
                              </div>
                            );
                          })}
                        </div>
                      );
                    });
                  })()}
                </div>
              </div>
            </PhoneShell2>

            {/* Pricing source visualization - right side */}
            <PricingViz t={t} />

            {/* Side caption */}
            <div style={{
              position: 'absolute', right: 36, top: 70, direction: 'rtl', maxWidth: 380,
              opacity: animate2({ from: 0, to: 1, start: 0.3, end: 0.9, ease: Easing2.easeOutCubic })(t),
            }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 12 }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--stamp)', letterSpacing: '0.12em' }}>
                  STEP 03
                </span>
                <span style={{ width: 50, height: 1, background: 'var(--rule-strong)' }} />
              </div>
              <h2 className="font-display" style={{
                fontSize: 48, lineHeight: 1, letterSpacing: '-0.02em', margin: 0,
              }}>
                תמחור <span style={{ color: 'var(--stamp)', fontStyle: 'italic' }}>חכם.</span>
              </h2>
              <p style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--ink-soft)', marginTop: 14 }}>
                תחילה המערכת לומדת את המחירים שלך - ובהמשך ההצעות יתומחרו באופן אוטומטי.
                <br />
                בנוסף - ניתן להגדיר ידנית מחירים קבועים.
              </p>
            </div>

            <Chyron2 num={3} label="תמחור חכם" />
          </div>
        );
      }}
    </Sprite>
  );
}

function PricingViz({ t }) {
  // Stack of "price book" cards, with values fly in
  return (
    <div style={{
      position: 'absolute', right: 80, top: 260,
      width: 320, direction: 'rtl',
    }}>
      <div className="smallcaps" style={{ fontSize: 10, color: 'var(--ink-muted)', marginBottom: 10 }}>
        ▸ המחירון שלך
      </div>
      {[
        { c: 'cat-floor', cat: 'ריצוף',   item: 'פורצלן 60×60', price: '145', delay: 0.8 },
        { c: 'cat-paint', cat: 'צבע',     item: 'קירות לבן מט', price: '19',  delay: 1.6 },
        { c: 'cat-demo',  cat: 'הריסות',  item: 'פירוק ריצוף',  price: '65',  delay: 0.4 },
      ].map((r, i) => {
        const e = animate2({ from: 0, to: 1, start: r.delay, end: r.delay + 0.5, ease: Easing2.easeOutBack })(t);
        if (e === 0) return null;
        return (
          <div key={i} style={{
            background: 'var(--panel)', border: '1px solid var(--rule)',
            padding: '10px 14px', borderRadius: 8, marginBottom: 8,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            opacity: e, transform: `translateY(${(1 - e) * -10}px) scale(${0.95 + e * 0.05})`,
            boxShadow: e > 0.5 ? `0 4px 12px -4px var(--${r.c})` : 'none',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span className="cat-dot" style={{ background: `var(--${r.c})` }} />
              <div>
                <div style={{ fontSize: 11, color: 'var(--ink-muted)' }}>{r.cat}</div>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{r.item}</div>
              </div>
            </div>
            <div className="font-mono" style={{ fontSize: 14, fontWeight: 700 }}>
              ₪{r.price}<span style={{ fontSize: 9, color: 'var(--ink-muted)' }}>/יח׳</span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════
// SCENE 5 · SEND VIA WHATSAPP  (24 → 30.5)
// ════════════════════════════════════════════════════════════════════
function Scene5WhatsApp() {
  return (
    <Sprite start={24} end={30.7}>
      {({ localTime: t, duration }) => {
        const exit = animate2({ from: 0, to: 1, start: duration - 0.4, end: duration, ease: Easing2.easeInCubic })(t);
        const op = 1 - exit;

        // Phone shows PDF preview shrinking; then becomes WhatsApp
        const transitionStart = 1.6;
        const showWhatsApp = t > transitionStart;

        // Tap effect on "send" button at 1.4s
        const tap = t > 1.2 && t < 1.7;

        return (
          <div style={{ position: 'absolute', inset: 0, opacity: op }}>
            {/* Phone */}
            <PhoneShell2 x={80} y={20} w={360} h={680}>
              {!showWhatsApp ? <PDFPreviewScreen t={t} tap={tap} /> : <WhatsAppScreen t={t - transitionStart} />}
            </PhoneShell2>

            {/* Side caption */}
            <div style={{
              position: 'absolute', right: 36, top: 70, direction: 'rtl', maxWidth: 380,
              opacity: animate2({ from: 0, to: 1, start: 0.3, end: 0.8, ease: Easing2.easeOutCubic })(t),
            }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 12 }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--stamp)', letterSpacing: '0.12em' }}>
                  STEP 04
                </span>
                <span style={{ width: 50, height: 1, background: 'var(--rule-strong)' }} />
              </div>
              <h2 className="font-display" style={{ fontSize: 48, lineHeight: 1, letterSpacing: '-0.02em', margin: 0 }}>
                שלח הצעה לחתימה ב<span style={{ color: '#008069', fontStyle: 'italic' }}>וואצאפ.</span>
              </h2>
              <p style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--ink-soft)', marginTop: 14 }}>
                לחיצה אחת - PDF ממותג + קישור לחתימה דיגיטלית, נשלח ישר לצ׳אט של הלקוח.
              </p>
            </div>

            <Chyron2 num={4} label="שליחה בוואצאפ" />
          </div>
        );
      }}
    </Sprite>
  );
}

function PDFPreviewScreen({ t, tap }) {
  return (
    <div style={{ position: 'absolute', inset: 0, paddingTop: 50, display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '6px 16px 6px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontSize: 16, color: 'var(--ink-muted)' }}>‹</span>
        <span style={{ fontSize: 13, fontWeight: 600 }}>תצוגה מקדימה</span>
        <span style={{ fontSize: 11, color: 'var(--stamp)', fontWeight: 600 }}>סטמפה</span>
      </div>

      {/* PDF preview - A4 mini */}
      <div style={{
        flex: 1, padding: '10px 16px 0',
        display: 'flex', flexDirection: 'column', alignItems: 'center',
      }}>
        <div style={{
          background: '#fff', border: '1px solid var(--rule)',
          borderRadius: 6, width: '88%', height: 220,
          padding: 14, position: 'relative',
          boxShadow: '0 8px 20px -8px rgba(26,20,14,0.25)',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid var(--rule)', paddingBottom: 5 }}>
            <div className="font-display" style={{ fontSize: 11, fontWeight: 600 }}>הצעת מחיר</div>
            <div className="font-mono" style={{ fontSize: 8 }}>#143</div>
          </div>
          {/* Body lines */}
          <div style={{ marginTop: 6, display: 'flex', flexDirection: 'column', gap: 3 }}>
            {[0.8, 0.65, 0.7, 0.6, 0.75, 0.5, 0.68].map((w, i) => (
              <div key={i} style={{ height: 4, width: `${w * 100}%`, background: 'var(--rule-strong)', borderRadius: 2 }} />
            ))}
          </div>
          {/* Stamp */}
          <div style={{ position: 'absolute', bottom: 14, right: 14 }}>
            <Seal2 size={48} rotation={-12} />
          </div>
          {/* Total */}
          <div style={{ position: 'absolute', bottom: 14, left: 14, fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700 }}>
            ₪ 21,948
          </div>
        </div>

        <div style={{ marginTop: 12, fontSize: 11, color: 'var(--ink-muted)' }}>
          PDF · 1 עמוד · מוכן לשליחה
        </div>
      </div>

      {/* Send button with WhatsApp icon */}
      <div style={{ padding: '10px 14px 18px' }}>
        <div style={{
          height: 50, borderRadius: 999,
          background: '#00A884', color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          fontSize: 14, fontWeight: 700,
          transform: tap ? 'scale(0.96)' : 'scale(1)',
          boxShadow: tap ? '0 0 0 6px rgba(0,168,132,0.2)' : '0 8px 22px -8px rgba(0,168,132,0.5)',
          transition: 'all 150ms',
        }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="#fff">
            <path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.7.1-.2.3-.8.9-.9 1.1-.2.2-.3.2-.6.1-.3-.1-1.2-.4-2.3-1.4-.8-.7-1.4-1.7-1.6-1.9-.2-.3 0-.4.1-.6.1-.1.3-.3.4-.5l.3-.4c.1-.2 0-.3-.1-.5l-.7-1.7c-.2-.4-.4-.4-.6-.4h-.5c-.2 0-.5.1-.7.3-.3.3-1 .9-1 2.3 0 1.3.9 2.7 1.1 2.8.1.2 1.9 3 4.6 4.2 1.6.7 2.2.7 3 .6.5-.1 1.6-.6 1.8-1.3.2-.6.2-1.2.2-1.3 0-.1-.2-.2-.5-.3z"/>
            <path d="M20.5 3.5C18.3 1.3 15.3 0 12 0 5.4 0 0 5.4 0 12c0 2.1.6 4.1 1.6 5.9L0 24l6.3-1.6c1.7.9 3.7 1.4 5.7 1.4h.1c6.6 0 12-5.4 12-12 0-3.2-1.3-6.2-3.6-8.3zM12 21.8c-1.8 0-3.6-.5-5.1-1.4l-.4-.2-3.8.9.9-3.7-.3-.4C2.4 15.5 2 13.8 2 12 2 6.5 6.5 2 12 2c2.7 0 5.2 1 7.1 2.9 1.9 1.9 2.9 4.4 2.9 7.1 0 5.5-4.5 9.8-10 9.8z"/>
          </svg>
          שלח ללקוח בוואטסאפ
        </div>
      </div>
    </div>
  );
}

function WhatsAppScreen({ t }) {
  // t starts at 0 when this screen appears
  const bubbleE = animate2({ from: 0, to: 1, start: 0.1, end: 0.35, ease: Easing2.easeOutBack })(t);
  const tickE  = animate2({ from: 0, to: 1, start: 0.6, end: 0.78, ease: Easing2.easeOutCubic })(t);
  const readE  = animate2({ from: 0, to: 1, start: 1.1, end: 1.25, ease: Easing2.easeOutCubic })(t);
  const replyE = animate2({ from: 0, to: 1, start: 1.6, end: 1.95, ease: Easing2.easeOutBack })(t);

  return (
    <div style={{
      position: 'absolute', inset: 0, paddingTop: 50,
      background: '#EFE7DE', display: 'flex', flexDirection: 'column',
    }}>
      {/* WhatsApp top bar - modern green */}
      <div style={{
        background: '#008069', color: '#fff',
        padding: '8px 14px', display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <span style={{ fontSize: 16 }}>‹</span>
        <div style={{
          width: 32, height: 32, borderRadius: 999, background: '#6B7C88',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 13, fontWeight: 600, color: '#fff',
        }}>ג</div>
        <div style={{ flex: 1, lineHeight: 1.1 }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>גלית מורן</div>
          <div style={{ fontSize: 10, opacity: 0.8 }}>מקוונת</div>
        </div>
        <span style={{ fontSize: 14 }}>⋮</span>
      </div>

      {/* Chat body */}
      <div style={{
        flex: 1, padding: '14px 12px',
        background: '#EFEAE2',
        backgroundImage: `radial-gradient(circle, rgba(0,0,0,0.025) 1px, transparent 1px)`,
        backgroundSize: '12px 12px',
        display: 'flex', flexDirection: 'column', gap: 8,
      }}>
        {/* Date pill */}
        <div style={{
          alignSelf: 'center',
          padding: '4px 10px', borderRadius: 6,
          background: 'rgba(225,245,254,0.92)', color: '#1F2C34',
          fontSize: 10, fontWeight: 500,
        }}>היום</div>

        {/* Out message - modern WA outgoing green */}
        <div style={{
          alignSelf: 'flex-end', maxWidth: '80%',
          opacity: bubbleE, transform: `translateY(${(1 - bubbleE) * 10}px) scale(${0.95 + bubbleE * 0.05})`,
          background: '#D9FDD3', borderRadius: 8, padding: 8,
          position: 'relative',
          boxShadow: '0 1px 0.5px rgba(0,0,0,0.13)',
        }}>
          {/* PDF attachment */}
          <div style={{
            background: 'rgba(255,255,255,0.7)', borderRadius: 6,
            padding: 8, display: 'flex', alignItems: 'center', gap: 8,
            marginBottom: 6,
          }}>
            <div style={{
              width: 32, height: 38, background: 'var(--stamp)', borderRadius: 4,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#fff', fontFamily: 'var(--font-mono)', fontSize: 8, fontWeight: 700,
              position: 'relative',
            }}>PDF
              <div style={{ position: 'absolute', top: 0, right: 0, width: 9, height: 9, background: 'rgba(0,0,0,0.2)', borderTopRightRadius: 4 }} />
            </div>
            <div style={{ flex: 1, minWidth: 0, color: '#1F2C34' }}>
              <div style={{ fontSize: 11, fontWeight: 600 }}>הצעה_143_קרליבך.pdf</div>
              <div style={{ fontSize: 9, opacity: 0.7 }}>148 KB · 1 עמוד</div>
            </div>
          </div>
          <div style={{ fontSize: 11.5, lineHeight: 1.4, color: '#1F2C34' }}>
            שלום גלית 👋
            <br />
            מצורפת הצעת המחיר לשיפוץ.
            <br />
            לחתימה דיגיטלית מאובטחת ↓
          </div>
          <div style={{
            fontSize: 10, color: '#027EB5', textDecoration: 'underline', marginTop: 6,
            fontFamily: 'var(--font-mono)',
            direction: 'ltr', textAlign: 'left',
          }}>
            stampa.app/q/143/sign
          </div>
          <div style={{
            fontSize: 9, color: '#667781', marginTop: 4, textAlign: 'left',
            display: 'flex', alignItems: 'center', gap: 3, justifyContent: 'flex-end',
          }}>
            13:42
            <span style={{ display: 'inline-flex', opacity: tickE, color: readE > 0 ? '#53BDEB' : '#667781' }}>
              <svg width="14" height="10" viewBox="0 0 14 10" fill="none">
                <path d="M1 5l3 3 5-7M5 5l3 3 5-7" stroke="currentColor" strokeWidth="1.2" fill="none"/>
              </svg>
            </span>
          </div>
        </div>

        {/* Typing indicator → reply */}
        {replyE > 0 && (
          <div style={{
            alignSelf: 'flex-start', maxWidth: '70%',
            opacity: replyE, transform: `translateY(${(1 - replyE) * 10}px)`,
            background: '#fff', borderRadius: 8, padding: '6px 10px',
            fontSize: 11.5, color: '#1F2C34', boxShadow: '0 1px 0.5px rgba(0,0,0,0.13)',
          }}>
            רגע פותחת...
            <div style={{ fontSize: 9, color: '#667781', marginTop: 3, textAlign: 'left' }}>13:43</div>
          </div>
        )}
      </div>
    </div>
  );
}

function DeliveryViz({ t }) {
  // Show: contractor avatar → arrow path → client phone (filling at end)
  const arrowE = animate2({ from: 0, to: 1, start: 2.0, end: 3.0, ease: Easing2.easeInOutCubic })(t);
  const clientE = animate2({ from: 0, to: 1, start: 3.5, end: 4.0, ease: Easing2.easeOutBack })(t);
  return (
    <div style={{
      position: 'absolute', right: 50, top: 280, width: 380, height: 160,
      direction: 'rtl',
    }}>
      {/* From */}
      <div style={{ position: 'absolute', right: 0, top: 40, textAlign: 'center' }}>
        <div style={{
          width: 64, height: 64, borderRadius: 999, background: 'var(--ink)',
          color: 'var(--paper)', display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--font-display)', fontSize: 26,
        }}>ד</div>
        <div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 6 }}>דוד · קבלן</div>
      </div>
      {/* Arrow path */}
      <svg style={{ position: 'absolute', right: 80, top: 50, width: 220, height: 60 }} viewBox="0 0 220 60">
        <path d="M5 30 Q 110 -10 215 30"
          stroke="var(--rule-strong)" strokeWidth="1.5" fill="none" strokeDasharray="4 4" />
        <path d="M5 30 Q 110 -10 215 30"
          stroke="var(--stamp)" strokeWidth="2.5" fill="none"
          strokeDasharray="250" strokeDashoffset={250 - arrowE * 250} />
        {/* Dot along path */}
        {arrowE > 0 && arrowE < 1 && (
          <circle r="5" fill="var(--stamp)">
            <animateMotion dur="1s" repeatCount="indefinite" path="M5 30 Q 110 -10 215 30" />
          </circle>
        )}
        {/* WhatsApp logo midway */}
        {arrowE > 0.3 && (
          <g transform="translate(110, 8)" opacity={Math.min(1, (arrowE - 0.3) * 3)}>
            <circle cx="0" cy="0" r="14" fill="#25D366" />
            <text x="0" y="3" textAnchor="middle" fontSize="14" fill="#fff" fontWeight="700">W</text>
          </g>
        )}
      </svg>
      {/* To */}
      <div style={{
        position: 'absolute', left: 0, top: 40, textAlign: 'center',
        opacity: clientE, transform: `scale(${0.7 + clientE * 0.3})`,
      }}>
        <div style={{
          width: 64, height: 64, borderRadius: 999, background: '#B8A78A',
          color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--font-display)', fontSize: 26,
          boxShadow: clientE > 0.5 ? '0 0 0 4px rgba(37,211,102,0.25)' : 'none',
        }}>ג</div>
        <div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 6 }}>גלית · לקוחה</div>
      </div>
    </div>
  );
}

window.VideoScenes_Part2 = { Scene3AI, Scene4Pricing, Scene5WhatsApp };
