// PreparaEntregaDemo — animated tour of the Wapido orders panel.
// Lives in the Capacidades / "Prepara comanda y entrega" tab.
//
// Timeline (looping, tight):
//   0.00 -  0.35  Card pops into "Recibidas" (snap-in with overshoot)
//   0.40 -  2.50  Toast "Nuevo pedido recibido" bottom-right
//   1.50 -  2.00  Modal opens
//   3.50 -  3.85  Modal scrolls to totals + buttons (snappy)
//   3.85 -  4.20  "Copiar pedido" press → toast "Copiado al portapapeles"
//   4.20 -  5.90  Toast visible while modal still shows (read time)
//   5.80 -  6.30  Modal closes (we go straight to panel)
//   6.40 -  6.85  Phone POPS in (scale + opacity), message already pasted
//   7.60 -  7.95  Message sends (input clears → green bubble)
//   8.10 -  8.70  Repartidor typing indicator
//   8.70 -  9.10  Repartidor response: "Voy en 5 🛵"
//   9.60 - 10.40  Phone fades out (smooth)
//  10.40 - 11.70  Card flies "Recibidas" → "En Preparación"
//  12.00 - 13.30  Card flies "En Preparación" → "Enviadas"
//  13.30 - 14.80  Hold final state, restart

const { useState: peState, useEffect: peEffect, useRef: peRef, useMemo: peMemo } = React;

const PE_TOTAL = 14.8;
const PE_MINT = '#43C98A';
const PE_MINT_DEEP = '#2EA36D';
const PE_MINT_SOFT = '#E8F6EE';

const peClamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));
const peEaseOut = (x) => 1 - Math.pow(1 - x, 3);
const peEaseInOut = (x) => x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2;
const pePhase = (t, a, b) => peClamp((t - a) / (b - a));

// type a string proportionally to progress (0..1)
function peTyped(str, p) {
  const n = Math.floor(peEaseOut(p) * str.length);
  return str.slice(0, n);
}

function usePeTime() {
  const [t, setT] = peState(0);
  peEffect(() => {
    let raf, start;
    const frame = (now) => {
      if (!start) start = now;
      const elapsed = (now - start) / 1000 % PE_TOTAL;
      setT(elapsed);
      raf = requestAnimationFrame(frame);
    };
    raf = requestAnimationFrame(frame);
    return () => cancelAnimationFrame(raf);
  }, []);
  return t;
}

// ── icons ──────────────────────────────────────────────
const PeIco = {
  bell: (c = 'currentColor') =>
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" /><path d="M13.7 21a2 2 0 0 1-3.4 0" />
    </svg>,

  copy: (c) =>
  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="9" y="9" width="13" height="13" rx="2" /><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
    </svg>,

  arrow: (c) =>
  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12h14M13 5l7 7-7 7" />
    </svg>,

  pin: (c) =>
  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" />
    </svg>,

  bike: (c) =>
  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="6" cy="17" r="3.5" /><circle cx="18" cy="17" r="3.5" /><path d="M6 17l4-7h5l3 7" /><path d="M14 5h3" />
    </svg>,

  cash: (c) =>
  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2" y="6" width="20" height="12" rx="2" /><circle cx="12" cy="12" r="2.5" />
    </svg>,

  note: (c) =>
  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M4 4h14l4 4v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z" /><path d="M8 9h8M8 13h6M8 17h4" />
    </svg>,

  close: (c) =>
  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 6l12 12M18 6L6 18" />
    </svg>,

  check: (c) =>
  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12l5 5L20 7" />
    </svg>

};

// ── the order card (the thing that travels across columns) ─
function PeOrderCard({ compact = false }) {
  return (
    <div style={{
      borderLeft: '3px solid #F09437',
      background: '#FFFFFF',
      border: '1px solid #EFEAE2',
      borderLeftWidth: 3,
      borderRadius: 6,
      padding: '8px 10px',
      fontFamily: 'Inter, system-ui, sans-serif',
      boxShadow: '0 1px 2px rgba(31,27,22,0.04)'
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 1 }}>
        <span style={{ fontSize: 11, fontWeight: 700, color: '#1F1B16' }}>Guillermo Carranza</span>
        <span style={{ fontSize: 10, color: '#8A7E6E' }}>#1</span>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
        <span style={{ fontSize: 9.5, color: '#8A7E6E' }}>09:08 a.m.</span>
        <span style={{ fontSize: 9.5, color: '#F09437', fontWeight: 600 }}>Domicilio</span>
      </div>
      <div style={{ fontSize: 8.5, color: '#8A7E6E', letterSpacing: '0.08em', fontWeight: 600, marginBottom: 2 }}>QUESADILLAS</div>
      <div style={{ fontSize: 10, color: '#1F1B16', lineHeight: 1.4 }}>
        <div><span style={{ fontWeight: 700, marginRight: 6 }}>1</span>Tinga de pollo</div>
        <div><span style={{ fontWeight: 700, marginRight: 6 }}>2</span>Queso</div>
      </div>
      {!compact &&
      <div style={{
        marginTop: 6,
        background: '#FFF8E8',
        border: '1px solid #F5E2B0',
        borderRadius: 4,
        padding: '4px 6px',
        fontSize: 8.5, color: '#7C5E18',
        display: 'flex', alignItems: 'center', gap: 4,
        lineHeight: 1.2
      }}>
          <span>💬</span>
          <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', minWidth: 0, flex: 1 }}>
            Sin grasa todo por favor. Accede por la entrada (pluma)…
          </span>
        </div>
      }
      <div style={{
        marginTop: 6,
        display: 'inline-block',
        border: '1px solid #E5E1D8',
        borderRadius: 999,
        padding: '1px 8px',
        fontSize: 9, color: '#5C5247'
      }}>Efectivo</div>
    </div>);

}

// ── the 3-column board ─────────────────────────────────
function PeBoard({ colPos, cardOpacity, cardScale, cardLift, dimmed }) {
  // colPos: fractional column index 0..2 (Recibidas → Preparación → Enviadas)
  // The card lives absolutely-positioned inside the board, centered in
  // its current column.

  const Col = ({ label, color, count, isCardCol }) =>
  <div style={{
    flex: 1,
    minWidth: 0,
    padding: '8px 6px',
    borderRight: '1px solid #ECEAE5'
  }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        background: color.bg, color: color.text,
        padding: '3px 9px', borderRadius: 999,
        fontSize: 10, fontWeight: 600
      }}>
          <span style={{ width: 5, height: 5, borderRadius: '50%', background: color.text, display: 'inline-block' }} />
          {label}
        </span>
        <span style={{ fontSize: 11, color: '#8A7E6E' }}>{count}</span>
      </div>
      <div style={{ marginTop: 14, minHeight: 80, position: 'relative' }}>
        {!isCardCol &&
      <div style={{ fontSize: 10, color: '#C9BEA8', textAlign: 'center', marginTop: 24 }}>No hay órdenes</div>
      }
      </div>
    </div>;


  const colIdx = Math.round(colPos);
  // Card centered horizontally in its column. Each column = 33.333% of board.
  const cardLeftPct = colPos * (100 / 3);
  const cardWidthCss = 'calc(33.333% - 24px)';
  const cardLeftCss = `calc(${cardLeftPct}% + 12px)`;

  return (
    <div style={{
      position: 'relative',
      height: '100%',
      display: 'flex', flexDirection: 'column',
      background: '#FAFAF7',
      filter: dimmed ? 'brightness(0.92)' : 'none',
      transition: 'filter 0.3s ease'
    }}>
      {/* Header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '12px 16px 8px',
        borderBottom: '1px solid #ECEAE5',
        background: '#FFFFFF'
      }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 700, color: '#1F1B16', letterSpacing: '-0.01em' }}>Panel de Órdenes</div>
          <div style={{ fontSize: 10, color: '#8A7E6E' }}>Gestiona las órdenes de hoy</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {PeIco.bell('#8A7E6E')}
          <span style={{
            background: PE_MINT, color: '#FFF',
            fontSize: 9.5, fontWeight: 700,
            padding: '3px 8px', borderRadius: 999,
            display: 'inline-flex', alignItems: 'center', gap: 5
          }}>
            <span style={{
              width: 5, height: 5, borderRadius: '50%', background: '#FFF',
              boxShadow: '0 0 0 0 rgba(255,255,255,0.7)',
              animation: 'pePulse 1.4s ease-out infinite'
            }} />
            Recibiendo
          </span>
          <span style={{
            width: 24, height: 14, background: PE_MINT, borderRadius: 999,
            position: 'relative'
          }}>
            <span style={{
              position: 'absolute', top: 2, left: 12,
              width: 10, height: 10, borderRadius: '50%', background: '#FFF',
              boxShadow: '0 1px 1px rgba(0,0,0,0.2)'
            }} />
          </span>
        </div>
      </div>

      {/* Columns */}
      <div style={{ flex: 1, display: 'flex', minHeight: 0, position: 'relative' }}>
        <Col label="Recibidas"
        color={{ bg: '#E3F0FB', text: '#2C7AB6' }}
        count={colIdx === 0 ? 1 : 0}
        isCardCol={colIdx === 0} />
        <Col label="En Preparación"
        color={{ bg: '#FFF1DE', text: '#C77410' }}
        count={colIdx === 1 ? 1 : 0}
        isCardCol={colIdx === 1} />
        <Col label="Enviadas"
        color={{ bg: PE_MINT_SOFT, text: PE_MINT_DEEP }}
        count={colIdx === 2 ? 1 : 0}
        isCardCol={colIdx === 2} />

        {/* the traveling card — absolutely positioned over the board */}
        {cardOpacity > 0.01 &&
        <div style={{
          position: 'absolute',
          top: 50,
          left: cardLeftCss,
          width: cardWidthCss,
          transform: `translateY(${cardLift}px) scale(${cardScale})`,
          opacity: cardOpacity,
          transition: 'none',
          pointerEvents: 'none',
          transformOrigin: 'top center'
        }}>
            <PeOrderCard />
          </div>
        }
      </div>
    </div>);

}

// ── the modal ──────────────────────────────────────────
function PeModal({ t, modalIn, scrollP, copyP, copiedP, movePrepP }) {
  // modalIn: 0..1 (open/close)
  // scrollP: 0..1 (scroll position in modal body)
  // copyP: 0..1 (copy button press)
  // copiedP: 0..1 (copied toast)
  // movePrepP: 0..1 (move to preparación button press)

  const showCopied = copiedP > 0.02;

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: `rgba(31,27,22,${0.35 * modalIn})`,
      opacity: modalIn,
      pointerEvents: 'none',
      transition: 'none',
      display: 'flex', alignItems: 'center', justifyContent: 'center'
    }}>
      <div style={{
        width: 280,
        height: 320,
        background: '#FFFFFF',
        borderRadius: 10,
        boxShadow: '0 20px 50px -10px rgba(31,27,22,0.35)',
        overflow: 'hidden',
        transform: `translateY(${(1 - modalIn) * 16}px) scale(${0.96 + 0.04 * modalIn})`,
        position: 'relative',
        display: 'flex', flexDirection: 'column',
        opacity: 1
      }}>
        {/* close button */}
        <div style={{
          position: 'absolute', top: 8, right: 8,
          width: 20, height: 20, borderRadius: 999,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#8A7E6E'
        }}>{PeIco.close('#8A7E6E')}</div>

        {/* Scrollable body */}
        <div style={{
          flex: 1,
          padding: '14px 16px',
          overflow: 'hidden',
          position: 'relative'
        }}>
          <div style={{
            transform: `translateY(${-scrollP * 158}px)`,
            transition: 'transform 0.5s cubic-bezier(0.4, 0, 0.2, 1)'
          }}>
            {/* Order # + status */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
              <span style={{ fontSize: 18, fontWeight: 700, color: '#1F1B16' }}>#1</span>
              <span style={{ flex: 1 }} />
              <span style={{
                background: '#3B91E0', color: '#FFF',
                padding: '2px 9px', borderRadius: 999,
                fontSize: 9.5, fontWeight: 600
              }}>Recibida</span>
            </div>
            <div style={{
              fontFamily: 'var(--mono)',
              fontSize: 8, color: '#C2BAA8', marginBottom: 12
            }}>ea775ed1-8d9d-4f70-b2fe-19e603017d90</div>

            {/* Customer */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <span style={{
                width: 26, height: 26, borderRadius: '50%',
                background: '#F0EBE0', color: '#5C5247',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 11, fontWeight: 700
              }}>G</span>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, color: '#1F1B16' }}>Guillermo Carranza</div>
                <div style={{ fontSize: 9.5, color: '#8A7E6E', fontFamily: 'var(--mono)' }}>📞 5219982915016</div>
              </div>
            </div>

            {/* Address row */}
            <div style={{
              border: '1px solid #ECEAE5', borderRadius: 6,
              padding: '6px 8px', display: 'flex', alignItems: 'center', gap: 6,
              marginBottom: 8
            }}>
              {PeIco.pin('#8A7E6E')}
              <span style={{ flex: 1, fontSize: 9.5, color: '#1F1B16', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                Plaza Azuna en Av. Sayil, local llamado Nantai
              </span>
              {PeIco.copy('#8A7E6E')}
            </div>

            {/* Pills */}
            <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
              <span style={{
                border: '1px solid #E5E1D8', borderRadius: 999,
                padding: '2px 8px', fontSize: 9.5, color: '#5C5247',
                display: 'inline-flex', alignItems: 'center', gap: 4
              }}>{PeIco.bike('#5C5247')} Domicilio</span>
              <span style={{
                border: '1px solid ' + PE_MINT, color: PE_MINT_DEEP,
                borderRadius: 999,
                padding: '2px 8px', fontSize: 9.5,
                display: 'inline-flex', alignItems: 'center', gap: 4
              }}>{PeIco.cash(PE_MINT_DEEP)} Efectivo</span>
            </div>

            {/* Notes block */}
            <div style={{
              background: '#FFF8E8',
              border: '1px solid #F5E2B0',
              borderRadius: 6,
              padding: '8px 10px',
              marginBottom: 12
            }}>
              <div style={{
                fontSize: 10, fontWeight: 700, color: '#9C7B1A',
                display: 'flex', alignItems: 'center', gap: 5, marginBottom: 3
              }}>
                <span>💬</span> Notas del cliente
              </div>
              <div style={{ fontSize: 9.5, color: '#7C5E18', lineHeight: 1.4 }}>
                Sin grasa todo por favor. Accede por la entrada (pluma) donde está el oxxo.
              </div>
            </div>

            {/* Products */}
            <div style={{
              borderTop: '1px solid #ECEAE5',
              paddingTop: 10,
              marginBottom: 8
            }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: '#1F1B16', marginBottom: 4 }}>Productos</div>
              <div style={{ fontSize: 8.5, color: '#8A7E6E', letterSpacing: '0.1em', fontWeight: 600, marginBottom: 4 }}>QUESADILLAS</div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, padding: '3px 0' }}>
                <span style={{ color: '#1F1B16' }}>1x Tinga De Pollo</span>
                <span style={{ color: '#1F1B16', fontVariantNumeric: 'tabular-nums' }}>$39</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, padding: '3px 0', borderBottom: '1px solid #ECEAE5' }}>
                <span style={{ color: '#1F1B16' }}>2x Queso</span>
                <span style={{ color: '#1F1B16', fontVariantNumeric: 'tabular-nums' }}>$78</span>
              </div>
            </div>

            {/* Totals */}
            <div style={{ paddingTop: 4, marginBottom: 12 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: '#5C5247', padding: '2px 0' }}>
                <span>Subtotal</span>
                <span style={{ fontVariantNumeric: 'tabular-nums' }}>$117</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: '#5C5247', padding: '2px 0' }}>
                <span>Envío</span>
                <span style={{ fontVariantNumeric: 'tabular-nums' }}>$50</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, padding: '4px 0', fontWeight: 700 }}>
                <span style={{ color: '#1F1B16' }}>Total</span>
                <span style={{ color: PE_MINT_DEEP, fontVariantNumeric: 'tabular-nums' }}>$167</span>
              </div>
            </div>

            {/* Action buttons */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, paddingBottom: 8 }}>
              <button style={{
                background: '#F4F1EB',
                border: 'none',
                borderRadius: 6,
                padding: '8px 10px',
                fontSize: 11, fontWeight: 600,
                color: '#1F1B16',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                transform: `scale(${1 - 0.05 * copyP})`,
                transition: 'transform 0.12s ease'
              }}>
                {PeIco.copy('#1F1B16')}
                Copiar pedido
              </button>
              <button style={{
                background: PE_MINT, color: '#FFF',
                border: 'none',
                borderRadius: 6,
                padding: '8px 10px',
                fontSize: 11, fontWeight: 700,
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                transform: `scale(${1 - 0.05 * movePrepP})`,
                transition: 'transform 0.12s ease'
              }}>
                Mover a Preparación  {PeIco.arrow('#FFF')}
              </button>
            </div>
          </div>

          {/* Scroll hint (right edge bar) */}
          <div style={{
            position: 'absolute',
            right: 4, top: 12, bottom: 12,
            width: 3,
            background: '#F0EBE0',
            borderRadius: 2
          }}>
            <div style={{
              width: '100%',
              height: 38,
              background: '#C2BAA8',
              borderRadius: 2,
              transform: `translateY(${scrollP * 220}px)`,
              transition: 'transform 0.5s cubic-bezier(0.4, 0, 0.2, 1)'
            }} />
          </div>
        </div>

        {/* Copied toast (top-center) */}
        {showCopied &&
        <div style={{
          position: 'absolute',
          top: 8 - copiedP * 4,
          left: '50%',
          transform: `translateX(-50%) translateY(${(1 - copiedP) * -6}px)`,
          opacity: copiedP,
          background: '#1F1B16',
          color: '#FFF',
          padding: '5px 12px',
          borderRadius: 999,
          fontSize: 10, fontWeight: 600,
          display: 'inline-flex', alignItems: 'center', gap: 6,
          boxShadow: '0 6px 16px rgba(31,27,22,0.25)',
          zIndex: 5
        }}>
            <span style={{
            width: 14, height: 14, borderRadius: '50%',
            background: PE_MINT,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center'
          }}>{PeIco.check('#FFF')}</span>
            Copiado al portapapeles
          </div>
        }
      </div>
    </div>);

}

// ── phone with WhatsApp chat to repartidor ─────────────
const PE_DELIVERY_MESSAGE =
`*Pedido #1 — Sabor Casero*

👤 Guillermo Carranza
📞 5219982915016
📍 Plaza Azuna en Av. Sayil, local llamado Nantai

📝 Notas: Sin grasa todo por favor. Accede por la entrada (pluma) donde está el oxxo.

🍽️ Productos:
• 1x Tinga De Pollo
• 2x Queso

💵 Total: $167 (Efectivo)`;

function PePhone({ phoneIn, pastedP, sentP, repartidorTypingActive, repartidorReplyP }) {
  // phoneIn: 0..1 (popup in)
  // pastedP: 0..1 (whether the message is pasted into the input)
  // sentP: 0..1 (sent bubble entry — when > 0.5 the input clears)
  // repartidorTypingActive: bool (show typing indicator)
  // repartidorReplyP: 0..1 (response bubble entry)

  const showPastedInInput = pastedP > 0.5 && sentP < 0.5;

  return (
    <div style={{
      position: 'absolute',
      inset: 0,
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      padding: '24px 0 0',
      pointerEvents: 'none',
      zIndex: 20
    }}>
      <div style={{
        width: 260,
        height: 380,
        background: '#FFFFFF',
        borderTopLeftRadius: 24,
        borderTopRightRadius: 24,
        overflow: 'hidden',
        boxShadow: '0 24px 60px -16px rgba(31,27,22,0.55), 0 6px 18px -4px rgba(31,27,22,0.22)',
        border: '1px solid rgba(31,27,22,0.08)',
        borderBottom: 'none',
        display: 'flex', flexDirection: 'column',
        fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
        transform: `translateY(${(1 - phoneIn) * 24}px) scale(${0.7 + 0.3 * phoneIn})`,
        opacity: phoneIn,
        transition: 'none',
        transformOrigin: 'bottom center'
      }}>
        {/* Header */}
        <div style={{
          background: '#075E54',
          color: '#FFF',
          padding: '9px 10px',
          display: 'flex', alignItems: 'center', gap: 8
        }}>
          <span style={{ fontSize: 16, opacity: 0.9 }}>‹</span>
          <div style={{
            width: 28, height: 28, borderRadius: '50%',
            background: '#5B7C99',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 13, color: '#FFF', fontWeight: 700
          }}>🛵</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12, fontWeight: 700 }}>Carlos · Repartidor</div>
            <div style={{ fontSize: 9.5, opacity: 0.85 }}>en línea</div>
          </div>
        </div>

        {/* Chat */}
        <div style={{
          flex: 1,
          background: '#E5DDD5',
          backgroundImage: 'repeating-linear-gradient(45deg, rgba(255,255,255,0.04) 0 2px, transparent 2px 6px)',
          padding: '10px 8px',
          overflow: 'hidden',
          display: 'flex', flexDirection: 'column',
          gap: 5,
          minHeight: 0
        }}>
          <div style={{
            alignSelf: 'center',
            background: '#E1F2FB',
            color: '#5A6F7B',
            padding: '2px 9px',
            borderRadius: 7,
            fontSize: 9, fontWeight: 500
          }}>HOY</div>

          {/* Sent message bubble (appears when sentP > 0) */}
          {sentP > 0 &&
          <div style={{
            alignSelf: 'flex-end',
            background: '#DCF8C6',
            padding: '6px 8px 5px',
            borderRadius: 7,
            borderTopRightRadius: 0,
            fontSize: 9.5, color: '#1F2937',
            maxWidth: '92%',
            boxShadow: '0 1px 0.5px rgba(0,0,0,0.13)',
            whiteSpace: 'pre-line',
            lineHeight: 1.32,
            opacity: sentP,
            transform: `translateY(${(1 - sentP) * 6}px) scale(${0.95 + 0.05 * sentP})`,
            transformOrigin: 'bottom right'
          }}>
              {PE_DELIVERY_MESSAGE}
              <span style={{
              fontSize: 8, color: '#8696A0',
              marginLeft: 5, float: 'right',
              marginTop: 2, marginBottom: -1,
              display: 'inline-flex', alignItems: 'center', gap: 3
            }}>
                09:09
                <svg width="11" height="7" viewBox="0 0 16 11" fill="#53BDEB" aria-hidden>
                  <path d="M11.07.21L6.34 5.7 4.62 4.21 3.45 5.4l3.04 2.62L12.43 1.4z" />
                  <path d="M15.07.21L10.34 5.7 9.5 4.97 8.34 6.16l1.42 1.24L15.7 1.4z" />
                </svg>
              </span>
            </div>
          }

          {/* Repartidor typing indicator */}
          {repartidorTypingActive &&
          <div style={{
            alignSelf: 'flex-start',
            background: '#FFFFFF',
            padding: '7px 10px',
            borderRadius: 7,
            borderTopLeftRadius: 0,
            display: 'inline-flex', gap: 3, alignItems: 'center',
            boxShadow: '0 1px 0.5px rgba(0,0,0,0.13)',
            width: 'fit-content'
          }}>
              {[0, 1, 2].map((i) =>
            <span key={i} style={{
              width: 5, height: 5, borderRadius: '50%',
              background: '#8696A0',
              animation: `peTyping 1.2s ${i * 0.18}s ease-in-out infinite`
            }} />
            )}
            </div>
          }

          {/* Repartidor reply bubble */}
          {repartidorReplyP > 0 &&
          <div style={{
            alignSelf: 'flex-start',
            background: '#FFFFFF',
            padding: '6px 8px 5px',
            borderRadius: 7,
            borderTopLeftRadius: 0,
            fontSize: 10.5, color: '#1F2937',
            maxWidth: '78%',
            boxShadow: '0 1px 0.5px rgba(0,0,0,0.13)',
            lineHeight: 1.3,
            opacity: repartidorReplyP,
            transform: `translateY(${(1 - repartidorReplyP) * 6}px) scale(${0.95 + 0.05 * repartidorReplyP})`,
            transformOrigin: 'bottom left'
          }}>
              Voy en 5 🛵
              <span style={{
              fontSize: 8, color: '#8696A0',
              marginLeft: 6, float: 'right',
              marginTop: 2, marginBottom: -1
            }}>
                09:10
              </span>
            </div>
          }
        </div>

        {/* Input bar */}
        <div style={{
          background: '#F0F0F0',
          padding: '7px 8px',
          display: 'flex', gap: 6, alignItems: 'flex-end',
          minHeight: 40
        }}>
          <div style={{
            flex: 1,
            background: '#FFF',
            borderRadius: 14,
            padding: '6px 10px',
            fontSize: 9.5,
            color: showPastedInInput ? '#1F1B16' : '#9AA0A6',
            display: 'flex', flexDirection: 'column',
            maxHeight: 130,
            overflow: 'hidden',
            position: 'relative',
            lineHeight: 1.3,
            fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
            whiteSpace: 'pre-wrap'
          }}>
            {showPastedInInput ?
            PE_DELIVERY_MESSAGE :

            <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ fontSize: 12 }}>😊</span>
                Mensaje
              </span>
            }
          </div>
          <div style={{
            width: 30, height: 30, borderRadius: '50%',
            background: '#075E54',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#FFF', fontSize: 11,
            flexShrink: 0
          }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="#FFF"><path d="M2 21l21-9L2 3v7l15 2-15 2z" /></svg>
          </div>
        </div>
      </div>
    </div>);

}

// ── captions ───────────────────────────────────────────
function PeCaption({ t }) {
  let caption = 'Pedido recibido…';
  if (t > 1.5) caption = 'Revisando detalles…';
  if (t > 3.85) caption = 'Copiando datos del pedido…';
  if (t > 6.40) caption = 'Pasando al repartidor…';
  if (t > 9.05) caption = 'Listo, repartidor avisado ✓';
  if (t > 10.4) caption = 'Moviendo a preparación…';
  if (t > 12.0) caption = 'Pedido en camino…';

  return (
    <div style={{
      background: PE_MINT_SOFT, color: PE_MINT_DEEP,
      borderRadius: 999,
      padding: '4px 10px',
      fontSize: 10, fontWeight: 600,
      display: 'inline-flex', alignItems: 'center', gap: 6
    }}>
      <span style={{
        width: 6, height: 6, borderRadius: '50%', background: PE_MINT_DEEP,
        display: 'inline-block',
        animation: 'pePulse 1.2s ease-out infinite'
      }} />
      {caption}
    </div>);

}

// ── main demo ──────────────────────────────────────────
function PreparaEntregaDemo() {
  const t = usePeTime();

  // ── derived animation state ────────────────────────────
  // Card pop-in: 0.0 → 0.35s with overshoot
  const popP = pePhase(t, 0.0, 0.35);
  // Scale overshoots to 1.12 at p=0.6, then settles to 1.0
  let cardScale;
  if (popP < 0.6) cardScale = peEaseOut(popP / 0.6) * 1.12;else
  cardScale = 1.12 - (popP - 0.6) / 0.4 * 0.12;
  if (popP >= 1) cardScale = 1;
  const cardOpacity = popP;

  // Modal: opens at 1.5, closes 5.8–6.3 (after "Copiado" has been seen).
  // After it closes we never reopen it.
  const modalIn = pePhase(t, 1.5, 2.0) * (1 - pePhase(t, 5.8, 6.3));

  // Scroll the modal body: 3.5 → 3.85 (snappier)
  const scrollP = pePhase(t, 3.5, 3.85);

  // Copy button press 3.85 → 4.25
  const copyP = pePhase(t, 3.85, 4.05) * (1 - pePhase(t, 4.15, 4.35));
  // Copied toast: appears 4.05 → fades 5.7 (a beat longer for read time)
  const copiedP = pePhase(t, 4.05, 4.35) * (1 - pePhase(t, 5.5, 6.0));

  // "Nuevo pedido recibido" toast: 0.4 → 2.5 (auto-dismiss before modal opens)
  const newOrderToastP = pePhase(t, 0.4, 0.7) * (1 - pePhase(t, 2.0, 2.5));

  // Phone pops in 6.40 → 6.85 (fast scale + opacity), fades out 9.60 → 10.40
  const phoneInP = peEaseOut(pePhase(t, 6.40, 6.85));
  const phoneOutP = peEaseInOut(pePhase(t, 9.60, 10.40));
  const phoneIn = phoneInP * (1 - phoneOutP);

  // Pasted message visible as soon as phone is mostly in
  const pastedP = pePhase(t, 6.60, 6.85);

  // Sent bubble appears: 7.60 → 7.95 (input clears, bubble shows)
  const sentP = pePhase(t, 7.60, 7.95);

  // Repartidor typing indicator: 8.10 → 8.70
  const repartidorTypingActive = t >= 8.10 && t < 8.70;
  // Repartidor response bubble appears: 8.70 → 9.05
  const repartidorReplyP = pePhase(t, 8.70, 9.05);

  // No "Mover a Preparación" press anymore (modal closed already)
  const movePrepP = 0;

  // Card travel between columns (kick off right after phone fades out)
  // 10.40 → 11.70  Recibidas (col 0) → En Preparación (col 1)
  // 12.00 → 13.30  En Preparación (col 1) → Enviadas (col 2)
  const moveA = peEaseInOut(pePhase(t, 10.40, 11.70));
  const moveB = peEaseInOut(pePhase(t, 12.00, 13.30));
  let colPos = 0;
  if (t >= 12.00) colPos = 1 + moveB;else
  if (t >= 10.40) colPos = moveA;

  // Subtle lift during moves (parabolic)
  let cardLift = 0;
  if (t >= 10.40 && t < 11.80) cardLift = -8 * Math.sin(Math.PI * pePhase(t, 10.40, 11.70));else
  if (t >= 12.00 && t < 13.40) cardLift = -8 * Math.sin(Math.PI * pePhase(t, 12.00, 13.30));

  // Slight scale bump on travel
  if (t >= 10.40 && t < 11.80) cardScale = 1 + 0.06 * Math.sin(Math.PI * pePhase(t, 10.40, 11.70));else
  if (t >= 12.00 && t < 13.40) cardScale = 1 + 0.06 * Math.sin(Math.PI * pePhase(t, 12.00, 13.30));

  // Modal opacity dimming when phone is visible (mostly irrelevant — modal is gone)
  const modalVisOpacity = 1 - 0.92 * phoneIn;

  // dim the board when phone is up
  const boardDimmed = phoneIn > 0.4;

  // url segment
  const urlSeg = t < 6.85 ? 'orders' :
  t < 10.4 ? 'chat' :
  'orders';

  return (
    <div style={{
      flex: 1,
      width: '100%',
      height: 580,
      maxHeight: 580,
      margin: '0 auto',
      borderRadius: 14,
      overflow: 'hidden',
      background: '#F7F6F2',
      border: '1px solid #E5E1D8',
      boxShadow: '0 24px 60px -28px rgba(31,27,22,0.32), 0 4px 12px -6px rgba(31,27,22,0.10)',
      fontFamily: 'Inter, system-ui, sans-serif',
      position: 'relative',
      display: 'flex', flexDirection: 'column'
    }}>
      {/* Top bar matches AprendeNegocioDemo style */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '8px 12px',
        background: '#FFFFFF',
        borderBottom: '1px solid #ECEAE5'
      }}>
        <span style={{ width: 9, height: 9, borderRadius: '50%', background: '#FF6058' }} />
        <span style={{ width: 9, height: 9, borderRadius: '50%', background: '#FFBD2E' }} />
        <span style={{ width: 9, height: 9, borderRadius: '50%', background: '#27C940' }} />
        <div style={{
          marginLeft: 14, flex: 1,
          background: '#F4F1EB', border: '1px solid #ECEAE5',
          borderRadius: 6,
          padding: '3px 10px',
          fontSize: 10.5, color: '#8A7E6E',
          fontFamily: 'var(--mono)',
          letterSpacing: '0.02em',
          display: 'flex', alignItems: 'center', gap: 6,
          maxWidth: 320
        }}>
          <span style={{ color: PE_MINT_DEEP, fontWeight: 600 }}>app.wapido.ai</span>
          <span style={{ color: '#C2BAA8' }}>/{urlSeg}</span>
        </div>
        <PeCaption t={t} />
      </div>

      {/* Body: dashboard with overlayed modal + phone */}
      <div style={{
        flex: 1,
        position: 'relative',
        background: '#FAFAF7',
        minHeight: 0,
        overflow: 'hidden'
      }}>
        <PeBoard
          colPos={colPos}
          cardOpacity={cardOpacity}
          cardScale={cardScale}
          cardLift={cardLift}
          dimmed={boardDimmed} />
        

        {modalIn > 0.01 &&
        <div style={{ opacity: modalVisOpacity, position: 'absolute', inset: 0 }}>
            <PeModal
            t={t}
            modalIn={modalIn}
            scrollP={scrollP}
            copyP={copyP}
            copiedP={copiedP}
            movePrepP={movePrepP} />
          
          </div>
        }

        {phoneIn > 0.01 &&
        <PePhone
          phoneIn={phoneIn}
          pastedP={pastedP}
          sentP={sentP}
          repartidorTypingActive={repartidorTypingActive}
          repartidorReplyP={repartidorReplyP} />

        }

        {/* New-order toast (bottom-right of board) */}
        {newOrderToastP > 0.01 &&
        <div style={{
          position: 'absolute',
          right: 14,
          bottom: 14,
          opacity: newOrderToastP,
          transform: `translateY(${(1 - newOrderToastP) * 10}px)`,
          background: '#FFFFFF',
          border: '1px solid #ECEAE5',
          boxShadow: '0 12px 28px -10px rgba(31,27,22,0.32), 0 2px 6px rgba(31,27,22,0.10)',
          borderRadius: 10,
          padding: '10px 12px',
          display: 'flex', alignItems: 'center', gap: 10,
          minWidth: 200,
          zIndex: 15
        }}>
            <span style={{
            width: 28, height: 28, borderRadius: '50%',
            background: PE_MINT_SOFT,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0
          }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={PE_MINT_DEEP} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" />
                <path d="M13.7 21a2 2 0 0 1-3.4 0" />
              </svg>
            </span>
            <div style={{ lineHeight: 1.2 }}>
              <div style={{ fontSize: 11.5, fontWeight: 700, color: '#1F1B16' }}>Nuevo pedido recibido</div>
              <div style={{ fontSize: 10, color: '#8A7E6E', marginTop: 1 }}>Guillermo Carranza · #1</div>
            </div>
          </div>
        }
      </div>

      <style>{`
        @keyframes pePulse {
          0% { box-shadow: 0 0 0 0 rgba(46,163,109,0.5); }
          70% { box-shadow: 0 0 0 6px rgba(46,163,109,0); }
          100% { box-shadow: 0 0 0 0 rgba(46,163,109,0); }
        }
        @keyframes peTyping {
          0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
          30% { transform: translateY(-3px); opacity: 1; }
        }
      `}</style>
    </div>);

}

window.PreparaEntregaDemo = PreparaEntregaDemo;