// TomaLaOrdenDemo — animated WhatsApp conversation between a customer
// and Wapi (the Wapido agent). Lives inside the Capacidades / "Toma
// la orden" tab on the landing.

const { useState: tlState, useEffect: tlEffect, useRef: tlRef, useMemo: tlMemo } = React;

// ── conversation timeline ──────────────────────────────
// `t` = seconds at which the bubble fully appears.
// `typingFrom` (agent only) = when the "typing..." indicator starts.
const TLO_MESSAGES = [
{ t: 1.2, from: 'them', text: 'Holaa! Tienen servicio?' },
{ t: 3.8, from: 'us', typingFrom: 2.2, text: 'Sí, claro! ¿Qué le vamos a preparar?' },
{ t: 5.6, from: 'them', text: '¿Tienen de todo?' },
{ t: 8.4, from: 'us', typingFrom: 6.6, text: 'Sii, solo no tenemos asada de res.' },
{ t: 10.6, from: 'them', text: 'Perfecto, me da 2 de tinga y una de jamaica porfavor 🙏' },
{ t: 13.6, from: 'us', typingFrom: 11.6, text: 'Va! ¿Sería a domicilio o para recoger en sucursal?' },
{ t: 15.6, from: 'them', kind: 'location' },
{ t: 18.4, from: 'us', typingFrom: 16.4, text: 'Perfecto, a su domicilio serían $40 de envío.' },
{ t: 20.2, from: 'them', text: 'Está bien!' },
{ t: 23.4, from: 'us', typingFrom: 21.0, kind: 'summary' },
{ t: 25.2, from: 'them', text: 'Sii!' },
{ t: 28.0, from: 'us', typingFrom: 26.0, text: 'Perfecto, ya enviamos su pedido a cocina 👨‍🍳🛵' },
{ t: 29.6, from: 'them', text: 'Muchas gracias!' }];


const TLO_TOTAL = 33.5; // seconds before loop restart

// ── time hook ──────────────────────────────────────────
function useTloTime() {
  const [t, setT] = tlState(0);
  tlEffect(() => {
    let raf, start;
    const frame = (now) => {
      if (!start) start = now;
      const elapsed = (now - start) / 1000 % TLO_TOTAL;
      setT(elapsed);
      raf = requestAnimationFrame(frame);
    };
    raf = requestAnimationFrame(frame);
    return () => cancelAnimationFrame(raf);
  }, []);
  return t;
}

// ── helpers ────────────────────────────────────────────
const tloClamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));
const tloEaseOut = (x) => 1 - Math.pow(1 - x, 3);

// ── bubble pieces ──────────────────────────────────────
function TloBubble({ msg, t, isLast, nextMsg, prevMsg }) {
  // Animate bubble entry: opacity 0→1, translateY 8→0, scale 0.96→1 over 240ms after msg.t
  const age = t - msg.t;
  const enter = tloEaseOut(tloClamp(age / 0.24));

  const us = msg.from === 'us';
  const sameDirAsPrev = prevMsg && prevMsg.from === msg.from;
  const sameDirAsNext = nextMsg && nextMsg.from === msg.from;

  const baseBubble = {
    background: us ? '#DCF8C6' : '#FFFFFF',
    color: '#1F2937',
    padding: msg.kind === 'location' ? '4px 4px 4px 4px' : '5px 8px 4px',
    borderRadius: 7,
    fontSize: 13, lineHeight: 1.35,
    boxShadow: '0 1px 0.5px rgba(0,0,0,0.13)',
    position: 'relative',
    borderTopLeftRadius: !us && !sameDirAsPrev ? 0 : 7,
    borderTopRightRadius: us && !sameDirAsPrev ? 0 : 7,
    opacity: enter,
    transform: `translateY(${(1 - enter) * 8}px) scale(${0.97 + 0.03 * enter})`,
    transformOrigin: us ? 'bottom right' : 'bottom left',
    transition: 'none',
    maxWidth: msg.kind === 'summary' ? 240 : 220,
    whiteSpace: msg.kind === 'summary' ? 'pre-line' : 'normal'
  };

  const timeStamp =
  <span style={{
    fontSize: 9.5, color: '#8696A0',
    marginLeft: 6, float: 'right',
    marginTop: 2, marginBottom: -2,
    display: 'inline-flex', alignItems: 'center', gap: 3
  }}>
      {msg.time || '2:18 p. m.'}
      {us &&
    <svg width="13" height="9" 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>;


  return (
    <div style={{
      alignSelf: us ? 'flex-end' : 'flex-start',
      maxWidth: '82%',
      marginTop: sameDirAsPrev ? 2 : 6
    }}>
      <div style={baseBubble}>
        {msg.kind === 'location' && <TloLocationCard />}
        {msg.kind === 'summary' &&
        <div style={{
          padding: '6px 8px 2px',
          fontSize: 13, lineHeight: 1.45
        }}>
            <div>Entonces así quedaría su pedido:</div>
            <div style={{ marginTop: 6 }}>
              {'• 2 quesadillas de tinga'}<br />
              {'• 1 jamaica'}
            </div>
            <div style={{ marginTop: 8, fontVariantNumeric: 'tabular-nums' }}>
              {'Subtotal: $96'}<br />
              {'Envío: $40'}<br />
              <span style={{ fontWeight: 700 }}>{'Total: $136'}</span>
            </div>
            <div style={{ marginTop: 8 }}>¿Me confirma su orden por favor?</div>
            {timeStamp}
          </div>
        }
        {msg.text &&
        <div style={{
          padding: msg.kind === 'location' ? '6px 6px 2px' : 0,
          fontSize: 13, lineHeight: 1.35
        }}>
            {msg.text}
            {timeStamp}
          </div>
        }
        {!msg.text && msg.kind !== 'summary' && timeStamp}
      </div>
    </div>);

}

function TloTypingBubble() {
  return (
    <div style={{
      alignSelf: 'flex-start',
      background: '#FFFFFF',
      padding: '9px 14px',
      borderRadius: 7,
      marginTop: 6,
      display: 'inline-flex', gap: 4, 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: 6, height: 6, borderRadius: '50%',
        background: '#8696A0',
        animation: `tloTyping 1.2s ${i * 0.18}s ease-in-out infinite`
      }} />
      )}
    </div>);

}

// ── location card (Google Maps preview) ────────────────
function TloLocationCard() {
  return (
    <div style={{
      width: 220,
      borderRadius: 5,
      overflow: 'hidden',
      background: '#E8EEEA'
    }}>
      <div style={{
        height: 110,
        background: '#E8EEEA',
        position: 'relative',
        backgroundImage:
        // Roads
        'linear-gradient(90deg, transparent 0 18%, #FFFFFF 18% 22%, transparent 22% 60%, #FFFFFF 60% 64%, transparent 64%),' +
        'linear-gradient(0deg, transparent 0 30%, #FFFFFF 30% 33%, transparent 33% 65%, #FFFFFF 65% 68%, transparent 68%),' +
        // Park / blocks
        'linear-gradient(135deg, #D5E5D2 0%, #D5E5D2 50%, transparent 50%),' +
        'linear-gradient(45deg, #EAE2C8 0%, #EAE2C8 35%, transparent 35%)'
      }}>
        {/* River */}
        <div style={{
          position: 'absolute',
          top: '40%', left: -10, right: -10,
          height: 12,
          background: '#B8DDED',
          transform: 'rotate(-6deg)',
          opacity: 0.7
        }} />
        {/* Pin */}
        <div style={{
          position: 'absolute',
          left: '50%', top: '38%',
          transform: 'translate(-50%, -100%)'
        }}>
          <svg width="26" height="34" viewBox="0 0 26 34" fill="none">
            <path d="M13 1 C 6 1 1 6 1 13 C 1 22 13 33 13 33 C 13 33 25 22 25 13 C 25 6 20 1 13 1 Z"
            fill="#E53935" stroke="#FFFFFF" strokeWidth="1.5" />
            <circle cx="13" cy="13" r="4.5" fill="#FFFFFF" />
          </svg>
        </div>
      </div>
      <div style={{
        padding: '8px 10px',
        background: '#FFFFFF',
        borderTop: '1px solid #E0E0E0',
        display: 'flex', alignItems: 'flex-start', gap: 8
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="#5A6F7B" aria-hidden style={{ marginTop: 2, flexShrink: 0 }}>
          <path d="M12 2C8 2 5 5 5 9c0 5 7 13 7 13s7-8 7-13c0-4-3-7-7-7zm0 9.5a2.5 2.5 0 110-5 2.5 2.5 0 010 5z" />
        </svg>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: '#1F2937', lineHeight: 1.25 }}>
            Mi ubicación
          </div>
          <div style={{ fontSize: 10.5, color: '#5A6F7B', marginTop: 1 }}>
            Av. Reforma 234, depto 5
          </div>
        </div>
      </div>
    </div>);

}

// ── order summary card (user-fillable image slot) ──────
function TloSummaryCard() {
  return (
    <div style={{
      width: 232,
      borderRadius: 6,
      overflow: 'hidden',
      background: '#F0F0F0',
      display: 'block'
    }}>
      <image-slot
        id="tlo-summary"
        shape="rounded"
        radius="6"
        placeholder="Imagen del resumen"
        style={{ width: '100%', height: '180px', display: 'block' }}>
      </image-slot>
    </div>);

}

// ── phone chrome ───────────────────────────────────────
function TloPhoneHeader() {
  return (
    <div style={{
      background: '#075E54',
      color: '#FFFFFF',
      padding: '10px 12px',
      display: 'flex', alignItems: 'center', gap: 10,
      fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'
    }}>
      <span style={{ fontSize: 18, opacity: 0.9, marginRight: -4 }}>‹</span>
      <div style={{
        width: 32, height: 32, borderRadius: '50%',
        background: '#FFC9A8',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 16, flexShrink: 0
      }}>🌮</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 14, fontWeight: 600, letterSpacing: '-0.005em',
          display: 'flex', alignItems: 'center', gap: 4
        }}>
          <span>Tu Restaurante</span>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="#25D366" aria-hidden>
            <path d="M12 1l3.09 1.7L18.6 2.7l1 3.5 3.5 1-1 3.5 1 3.5-3.5 1-1 3.5-3.5-1-3.1 1.7-3.1-1.7-3.5 1-1-3.5-3.5-1 1-3.5-1-3.5 3.5-1 1-3.5 3.5 1z" />
            <path d="M9.5 12.5l2 2 4-4.5" stroke="#FFF" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>
        <div style={{ fontSize: 11, opacity: 0.85 }}>en línea</div>
      </div>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="#FFFFFF" opacity="0.85"><path d="M15 3.5l1.4 1.4-3.5 3.5h6.6V10h-6.6l3.5 3.6L15 15l-6-6 6-5.5z" transform="rotate(180 12 9.25)" /></svg>
      <span style={{ fontSize: 18, opacity: 0.9, letterSpacing: 2 }}>⋮</span>
    </div>);

}

function TloInputBar() {
  return (
    <div style={{
      background: '#F0F0F0',
      padding: '8px 10px',
      display: 'flex', gap: 8, alignItems: 'center'
    }}>
      <div style={{
        flex: 1,
        background: '#FFF',
        borderRadius: 20,
        padding: '7px 14px',
        fontSize: 12.5,
        color: '#9AA0A6',
        display: 'flex', alignItems: 'center', gap: 8
      }}>
        <span style={{ fontSize: 14 }}>😊</span>
        Mensaje
        <span style={{ flex: 1 }} />
        <span style={{ fontSize: 14, opacity: 0.6 }}>📎</span>
      </div>
      <div style={{
        width: 34, height: 34, borderRadius: '50%',
        background: '#075E54',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: '#FFF', fontSize: 13
      }}>🎤</div>
    </div>);

}

// ── caption pill (matches AprendeNegocioDemo) ──────────
function TloCaption({ t }) {
  // Pick caption based on conversation phase
  let caption = 'Recibiendo pedido…';
  if (t > 11) caption = 'Tomando la orden…';
  if (t > 19) caption = 'Calculando envío…';
  if (t > 22) caption = 'Confirmando pedido…';
  if (t > 27) caption = 'Enviado a cocina ✓';

  return (
    <div style={{
      background: '#E8F6EE', color: '#2EA36D',
      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: '#2EA36D',
        display: 'inline-block',
        animation: 'tloPulse 1.2s ease-out infinite'
      }} />
      {caption}
    </div>);

}

// ── main demo ──────────────────────────────────────────
function TomaLaOrdenDemo() {
  const t = useTloTime();
  const chatRef = tlRef(null);
  const stackRef = tlRef(null);
  const [scrollOffset, setScrollOffset] = tlState(0);

  // Which messages are visible (have fully entered)
  const visibleMessages = tlMemo(
    () => TLO_MESSAGES.filter((m) => t >= m.t - 0.24),
    [t]
  );

  // Is there an agent message currently in "typing" state?
  const typingNext = TLO_MESSAGES.find(
    (m) => m.typingFrom !== undefined && t >= m.typingFrom && t < m.t - 0.24
  );

  // Measure content height and compute target scroll offset
  tlEffect(() => {
    const measure = () => {
      if (!chatRef.current || !stackRef.current) return;
      const containerH = chatRef.current.clientHeight;
      const contentH = stackRef.current.scrollHeight;
      const target = Math.max(0, contentH - containerH);
      setScrollOffset(target);
    };
    // run after layout settles (next frame + a small delay for bubble entry)
    const r1 = requestAnimationFrame(measure);
    const tm = setTimeout(measure, 260);
    return () => {cancelAnimationFrame(r1);clearTimeout(tm);};
  }, [visibleMessages.length, !!typingNext]);

  // Overall progress for bottom bar
  const progress = tloClamp(t / TLO_TOTAL);

  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 with caption */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '10px 14px',
        background: '#FFFFFF',
        borderBottom: '1px solid #ECEAE5'
      }}>
        <div style={{
          fontFamily: 'var(--mono)',
          fontSize: 10, color: '#8A7E6E',
          letterSpacing: '0.08em', textTransform: 'uppercase',
          display: 'flex', alignItems: 'center', gap: 6
        }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#8A7E6E" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <rect x="6" y="2" width="12" height="20" rx="2.5" />
            <path d="M11 18h2" />
          </svg>
          Conexión directa a tu WhatsApp Business
        </div>
        <div style={{ flex: 1 }} />
        <TloCaption t={t} />
      </div>

      {/* phone canvas */}
      <div style={{
        flex: 1,
        background: '#F7F6F2',
        display: 'flex', alignItems: 'stretch', justifyContent: 'center',
        padding: '18px 0 0',
        minHeight: 0,
        overflow: 'hidden',
        position: 'relative'
      }}>
        {/* The phone */}
        <div style={{
          width: 320,
          flexShrink: 0,
          background: '#FFFFFF',
          borderTopLeftRadius: 24,
          borderTopRightRadius: 24,
          overflow: 'hidden',
          boxShadow: '0 18px 32px -16px rgba(31,27,22,0.22), 0 2px 6px -2px rgba(31,27,22,0.10)',
          border: '1px solid rgba(31,27,22,0.08)',
          borderBottom: 'none',
          display: 'flex', flexDirection: 'column'
        }}>
          <TloPhoneHeader />

          {/* Chat viewport (clips, no native scroll) */}
          <div
            ref={chatRef}
            className="tlo-chat-scroll"
            style={{
              height: 380,
              flexShrink: 0,
              background: '#E5DDD5',
              backgroundImage:
              'repeating-linear-gradient(45deg, rgba(255,255,255,0.04) 0 2px, transparent 2px 6px)',
              overflow: 'hidden',
              position: 'relative'
            }}>
            
            {/* Stack that slides up as content grows */}
            <div
              ref={stackRef}
              style={{
                padding: '12px 10px 14px',
                display: 'flex', flexDirection: 'column',
                gap: 0,
                transform: `translateY(${-scrollOffset}px)`,
                transition: 'transform 0.45s cubic-bezier(0.4, 0, 0.2, 1)',
                willChange: 'transform'
              }}>
              
              {/* Date pill */}
              <div style={{
                alignSelf: 'center',
                background: '#E1F2FB',
                color: '#5A6F7B',
                padding: '3px 10px',
                borderRadius: 8,
                fontSize: 10.5, fontWeight: 500,
                marginBottom: 6,
                boxShadow: '0 1px 1px rgba(0,0,0,0.06)'
              }}>HOY</div>

              {visibleMessages.map((m, i) =>
              <TloBubble
                key={i}
                msg={m}
                t={t}
                prevMsg={visibleMessages[i - 1]}
                nextMsg={visibleMessages[i + 1]} />

              )}

              {typingNext && <TloTypingBubble />}

              {/* spacer so last message isn't glued to input */}
              <div style={{ height: 4, flexShrink: 0 }} />
            </div>
          </div>

          <TloInputBar />
        </div>
      </div>

      {/* progress bar removed */}

      <style>{`
        @keyframes tloTyping {
          0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
          30% { transform: translateY(-3px); opacity: 1; }
        }
        @keyframes tloPulse {
          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); }
        }
        .tlo-chat-scroll { scrollbar-width: none; }
        .tlo-chat-scroll::-webkit-scrollbar { width: 0; height: 0; display: none; }
      `}</style>
    </div>);

}

window.TomaLaOrdenDemo = TomaLaOrdenDemo;