// ChatDemo.jsx — animated WhatsApp conversation inside the iOS frame
// Exports to window: ChatDemo

const SCRIPTS = {
  es: [
    { side: 'in', text: '¡Hola! ¿Tienen cita para limpieza dental esta semana? 🦷' },
    { side: 'out', typing: 1100, text: '¡Hola! Claro 😊 Déjame revisar la agenda…' },
    { side: 'out', typing: 900, card: { type: 'cal', title: 'Martes 14 · disponibles', slots: ['10:00', '12:30', '16:00'] } },
    { side: 'in', text: 'El de las 16:00 me viene perfecto' },
    { side: 'out', typing: 1200, text: '¡Listo! ✅ Te agendé el martes a las 16:00 y te envié la invitación al correo.' },
    { side: 'out', typing: 700, card: { type: 'done', title: 'Cita confirmada', sub: 'Mar 14 · 16:00 · Dra. Soto', tag: 'Google Calendar' } },
    { side: 'in', text: 'Gracias!! 🙌' },
    { side: 'out', typing: 800, text: 'Para eso estoy. Te recordaré un día antes 👋' },
  ],
  en: [
    { side: 'in', text: 'Hi! Any slot for a dental cleaning this week? 🦷' },
    { side: 'out', typing: 1100, text: 'Hi! Of course 😊 Let me check the calendar…' },
    { side: 'out', typing: 900, card: { type: 'cal', title: 'Tuesday 14 · available', slots: ['10:00', '12:30', '16:00'] } },
    { side: 'in', text: '4:00 PM works perfectly' },
    { side: 'out', typing: 1200, text: 'Done! ✅ Booked you Tuesday at 4:00 PM and sent the invite to your email.' },
    { side: 'out', typing: 700, card: { type: 'done', title: 'Appointment confirmed', sub: 'Tue 14 · 4:00 PM · Dr. Soto', tag: 'Google Calendar' } },
    { side: 'in', text: 'Thank you!! 🙌' },
    { side: 'out', typing: 800, text: 'Anytime. I’ll remind you a day before 👋' },
  ],
};

function Tick() {
  return <span className="tick">✓✓</span>;
}

function CalCard({ card, lang }) {
  return (
    <div>
      <div className="mini">
        <div className="ic" style={{ background: '#1A73E8' }}>
          <BrandIcon name="calendar" style={{ width: 22, height: 22 }} />
        </div>
        <div>
          <b>{card.title}</b>
          <span>{lang === 'es' ? 'Toca un horario' : 'Tap a time'}</span>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 6 }}>
        {card.slots.map((s, i) => (
          <div key={i} style={{
            flex: 1, textAlign: 'center', padding: '7px 0', borderRadius: 8,
            background: i === 2 ? 'var(--brand)' : 'rgba(27,91,255,.08)',
            color: i === 2 ? '#fff' : 'var(--brand)', fontWeight: 700, fontSize: '.78rem',
          }}>{s}</div>
        ))}
      </div>
    </div>
  );
}

function DoneCard({ card }) {
  return (
    <div className="mini" style={{ marginBottom: 0, background: 'rgba(37,211,102,.10)' }}>
      <div className="ic" style={{ background: 'var(--wa-green)' }}>
        <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5"/></svg>
      </div>
      <div style={{ flex: 1 }}>
        <b>{card.title}</b>
        <span>{card.sub}</span>
      </div>
      <span style={{
        fontFamily: 'var(--font-mono)', fontSize: '.6rem', fontWeight: 700,
        color: '#1A73E8', background: 'rgba(26,115,232,.1)', padding: '3px 7px', borderRadius: 6, whiteSpace: 'nowrap',
      }}>{card.tag}</span>
    </div>
  );
}

function ChatDemo({ lang = 'es' }) {
  const script = SCRIPTS[lang] || SCRIPTS.es;
  const t = (I18N[lang] || I18N.es).chat;
  const [count, setCount] = React.useState(0);
  const [typing, setTyping] = React.useState(false);
  const bodyRef = React.useRef(null);
  const timers = React.useRef([]);

  React.useEffect(() => {
    timers.current.forEach(clearTimeout);
    timers.current = [];
    setCount(0); setTyping(false);
    let i = 0;
    const run = () => {
      if (i >= script.length) {
        timers.current.push(setTimeout(() => { i = 0; setCount(0); timers.current.push(setTimeout(run, 500)); }, 3800));
        return;
      }
      const msg = script[i];
      const show = () => {
        setTyping(false);
        setCount(i + 1); i += 1;
        timers.current.push(setTimeout(run, 850));
      };
      if (msg.typing) {
        setTyping(true);
        timers.current.push(setTimeout(show, msg.typing));
      } else {
        timers.current.push(setTimeout(show, 250));
      }
    };
    timers.current.push(setTimeout(run, 700));
    return () => timers.current.forEach(clearTimeout);
  }, [lang]);

  React.useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [count, typing]);

  const shown = script.slice(0, count);

  return (
    <IOSDevice width={310} height={620} dark>
      <div className="wa">
        <div className="wa-top">
          <span className="wa-back">‹</span>
          <div className="wa-ava">
            <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>
          </div>
          <div>
            <div className="wa-name">{t.name}</div>
            <div className="wa-status"><span className="live"></span>{t.status}</div>
          </div>
          <div className="wa-icons">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M23 7l-7 5 7 5V7z"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.9.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
          </div>
        </div>

        <div className="wa-body" ref={bodyRef}>
          <div className="wa-day">{lang === 'es' ? 'HOY' : 'TODAY'}</div>
          {shown.map((m, idx) => (
            <div key={idx} className={'bubble ' + m.side + (m.card ? ' card-bubble' : '')}>
              {m.card ? (
                m.card.type === 'cal' ? <CalCard card={m.card} lang={lang} /> : <DoneCard card={m.card} />
              ) : (
                <span>{m.text}</span>
              )}
              {!m.card && (
                <span className="time">{'10:2' + (idx + 1)}{m.side === 'out' && <Tick />}</span>
              )}
            </div>
          ))}
          {typing && (
            <div className="typing"><i></i><i></i><i></i></div>
          )}
        </div>

        <div className="wa-input" style={{ paddingBottom: 26 }}>
          <div className="field">{t.field}</div>
          <div className="send">
            <svg viewBox="0 0 24 24" fill="#fff"><path d="M3 3l18 9-18 9 4-9-4-9z"/></svg>
          </div>
        </div>
      </div>
    </IOSDevice>
  );
}

Object.assign(window, { ChatDemo });
