// WhatsApp conversation inside a realistic iOS device frame.
// Uses IOSDevice/IOSStatusBar from ios-frame.jsx.

const WA_CONVERSATIONS = {
  celular: {
    contact: 'Reefly Eletro',
    sub: 'online',
    messages: [
      { who: 'them', text: 'Oi, vcs tem o iPhone 15 128gb?', time: '14:32' },
      { who: 'me',   text: 'Oi! Tenho sim 👋\nEm preto e azul.\nÀ vista sai por R$ 4.899 ou 12x de R$ 449 no cartão.', time: '14:32' },
      { who: 'them', text: 'E tem garantia?', time: '14:33' },
      { who: 'me',   text: '1 ano Apple + 90 dias de loja. Retira hoje mesmo na loja ou entrego amanhã cedo.', time: '14:33' },
      { who: 'them', text: 'Pode ser o preto. Como faço pra pagar?', time: '14:34' },
      { who: 'me',   text: 'Separei um no seu nome ✅\nTe mando o Pix agora. Assim que cair eu libero a retirada.', time: '14:34' },
    ],
  },
  fone: {
    contact: 'Reefly Eletro',
    sub: 'online',
    messages: [
      { who: 'them', text: 'Vcs tem fone bluetooth até R$ 300?', time: '10:12' },
      { who: 'me',   text: 'Oi! Tenho 3 opções boas nessa faixa:\n\n• JBL Tune 230 — R$ 249\n• QCY T13 — R$ 189\n• Haylou GT7 — R$ 159', time: '10:12' },
      { who: 'them', text: 'O JBL tem cancelamento de ruído?', time: '10:13' },
      { who: 'me',   text: 'Tem sim, ANC ativo + 40h de bateria com o case. Quer que eu separe um pra vc?', time: '10:13' },
      { who: 'them', text: 'Pode separar. Entrega pra Jatiúca?', time: '10:14' },
      { who: 'me',   text: 'Chego aí em 40 min 🛵\nPix ou cartão na entrega?', time: '10:14' },
    ],
  },
  smartwatch: {
    contact: 'Reefly Eletro',
    sub: 'online',
    messages: [
      { who: 'them', text: 'Quero dar um smartwatch de presente, tem sugestão?', time: '19:02' },
      { who: 'me',   text: 'Presente ótimo 🎁\nPra quem vai usar? (homem, mulher, mais esporte ou mais estilo?)', time: '19:02' },
      { who: 'them', text: 'Minha esposa, ela corre. Até uns 800', time: '19:03' },
      { who: 'me',   text: 'Perfeito. O Amazfit GTR Mini sai R$ 749 — GPS, monitor cardíaco, bateria 14 dias. Vem em rose ou preto.', time: '19:03' },
      { who: 'them', text: 'Tem em rose?', time: '19:04' },
      { who: 'me',   text: 'Tem 1 aqui 🌸 Separo?\nEmbalo pra presente sem custo.', time: '19:04' },
    ],
  },
};

function WAHeader({ contact, sub }) {
  return (
    <div style={{
      position: 'relative', zIndex: 5,
      paddingTop: 56, paddingBottom: 10,
      background: '#EDEDED',
      borderBottom: '0.5px solid rgba(0,0,0,0.08)',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center',
        padding: '0 12px', gap: 10,
      }}>
        {/* back chevron + avatar */}
        <svg width="11" height="20" viewBox="0 0 11 20" fill="none" style={{ flexShrink: 0 }}>
          <path d="M10 1L1 10l9 9" stroke="#007AFF" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
        <div style={{
          width: 36, height: 36, borderRadius: '50%',
          background: 'linear-gradient(135deg, #00C2CB 0%, #007A82 100%)',
          color: '#fff', fontWeight: 700, fontSize: 15,
          display: 'grid', placeItems: 'center',
          fontFamily: '-apple-system, system-ui',
          flexShrink: 0,
        }}>R</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: '-apple-system, system-ui',
            fontSize: 16, fontWeight: 600, color: '#000',
            letterSpacing: -0.3, lineHeight: 1.15,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>{contact}</div>
          <div style={{
            fontFamily: '-apple-system, system-ui',
            fontSize: 12, color: '#8E8E93', lineHeight: 1.2,
          }}>{sub}</div>
        </div>
        {/* video + call icons */}
        <div style={{ display: 'flex', gap: 18, alignItems: 'center', flexShrink: 0, marginRight: 4 }}>
          <svg width="22" height="14" viewBox="0 0 22 14" fill="none">
            <rect x="0.5" y="0.5" width="15" height="13" rx="3" stroke="#007AFF" strokeWidth="1.5"/>
            <path d="M16 4.5L21 2v10l-5-2.5v-5z" fill="#007AFF"/>
          </svg>
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
            <path d="M16.5 12.8l-2.8-1.3c-.6-.3-1.3-.1-1.7.4l-.7.9c-1.8-.9-3.3-2.4-4.2-4.2l.9-.7c.5-.4.7-1.1.4-1.7L7.1 3.4c-.3-.6-1-.9-1.6-.6L3.1 4c-.6.3-1 1-.9 1.6.4 4.8 4.4 8.8 9.2 9.2.7.1 1.3-.2 1.6-.8l1.2-2.4c.3-.6 0-1.4-.7-1.8z" fill="#007AFF"/>
          </svg>
        </div>
      </div>
    </div>
  );
}

function WABubble({ m }) {
  const isMe = m.who === 'me';
  const bg = isMe ? '#D9FDD3' : '#FFFFFF';
  const tail = isMe ? 'right' : 'left';
  return (
    <div style={{
      alignSelf: isMe ? 'flex-end' : 'flex-start',
      maxWidth: '78%',
      marginBottom: 4,
      position: 'relative',
    }}>
      <div style={{
        background: bg,
        borderRadius: 8,
        [tail === 'left' ? 'borderTopLeftRadius' : 'borderTopRightRadius']: 0,
        padding: '6px 9px 5px',
        boxShadow: '0 1px 0.5px rgba(0,0,0,0.13)',
        position: 'relative',
      }}>
        <div style={{
          fontFamily: '-apple-system, system-ui',
          fontSize: 14.5, color: '#111B21',
          lineHeight: 1.35, whiteSpace: 'pre-wrap',
          letterSpacing: -0.1,
          paddingRight: isMe ? 52 : 38,
        }}>{m.text}</div>
        <div style={{
          position: 'absolute', right: 8, bottom: 3,
          fontFamily: '-apple-system, system-ui',
          fontSize: 10.5, color: isMe ? '#667781' : '#8696A0',
          display: 'flex', alignItems: 'center', gap: 3,
        }}>
          {m.time}
          {isMe && (
            <svg width="15" height="11" viewBox="0 0 15 11" fill="none" style={{ marginLeft: 1 }}>
              <path d="M1 6l3 3 6.5-8M5.5 9l6.5-8" stroke="#53BDEB" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
            </svg>
          )}
        </div>
      </div>
    </div>
  );
}

function WAInputBar() {
  return (
    <div style={{
      padding: '8px 8px 10px',
      background: '#F0F0F0',
      borderTop: '0.5px solid rgba(0,0,0,0.08)',
      display: 'flex', alignItems: 'center', gap: 6,
    }}>
      {/* plus */}
      <div style={{
        width: 32, height: 32, borderRadius: '50%',
        background: '#fff',
        display: 'grid', placeItems: 'center',
        flexShrink: 0,
      }}>
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
          <path d="M8 2v12M2 8h12" stroke="#54656F" strokeWidth="2" strokeLinecap="round"/>
        </svg>
      </div>
      {/* input field */}
      <div style={{
        flex: 1, minHeight: 36,
        background: '#fff', borderRadius: 20,
        padding: '8px 14px',
        fontFamily: '-apple-system, system-ui',
        fontSize: 15, color: '#8696A0',
        display: 'flex', alignItems: 'center',
      }}>Mensagem</div>
      {/* mic */}
      <div style={{
        width: 36, height: 36, borderRadius: '50%',
        background: '#00A884',
        display: 'grid', placeItems: 'center',
        flexShrink: 0,
      }}>
        <svg width="16" height="18" viewBox="0 0 16 18" fill="none">
          <rect x="5" y="1" width="6" height="10" rx="3" fill="#fff"/>
          <path d="M2 8a6 6 0 0012 0M8 14v3" stroke="#fff" strokeWidth="1.6" strokeLinecap="round" fill="none"/>
        </svg>
      </div>
    </div>
  );
}

function WAScreen({ kind }) {
  const bodyRef = React.useRef(null);
  const conv = WA_CONVERSATIONS[kind] || WA_CONVERSATIONS.celular;
  const [visible, setVisible] = React.useState(0);
  const [typing, setTyping] = React.useState(false);

  React.useEffect(() => {
    setVisible(0);
    setTyping(false);
    let cancelled = false;
    const run = async () => {
      for (let i = 0; i < conv.messages.length; i++) {
        if (cancelled) return;
        const m = conv.messages[i];
        if (m.who === 'me' && i > 0) {
          setTyping(true);
          await new Promise(r => setTimeout(r, 900));
          if (cancelled) return;
          setTyping(false);
        } else {
          await new Promise(r => setTimeout(r, 500));
        }
        if (cancelled) return;
        setVisible(i + 1);
      }
    };
    run();
    return () => { cancelled = true; };
  }, [kind]);

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

  return (
    <div style={{
      display: 'flex', flexDirection: 'column',
      height: '100%',
      background: '#E5DDD5',
      backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='80' height='80' viewBox='0 0 80 80'><g fill='%23C2B8A8' opacity='0.18'><circle cx='10' cy='10' r='1'/><circle cx='50' cy='30' r='1'/><circle cx='30' cy='60' r='1'/><circle cx='70' cy='70' r='1'/></g></svg>")`,
    }}>
      <WAHeader contact={conv.contact} sub={conv.sub} />
      <div ref={bodyRef} style={{
        flex: 1, overflowY: 'auto',
        padding: '12px 10px 6px',
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{
          alignSelf: 'center',
          background: '#FCF4CB',
          padding: '4px 10px',
          borderRadius: 6,
          fontFamily: '-apple-system, system-ui',
          fontSize: 11.5, color: '#54656F',
          marginBottom: 12,
          boxShadow: '0 1px 0.5px rgba(0,0,0,0.08)',
        }}>HOJE</div>

        {conv.messages.slice(0, visible).map((m, i) => (
          <WABubble key={i} m={m} />
        ))}

        {typing && (
          <div style={{
            alignSelf: 'flex-start',
            background: '#fff',
            padding: '10px 14px',
            borderRadius: 8,
            borderTopLeftRadius: 0,
            boxShadow: '0 1px 0.5px rgba(0,0,0,0.13)',
            display: 'flex', gap: 4, alignItems: 'center',
            marginBottom: 4,
          }}>
            {[0,1,2].map(i => (
              <span key={i} style={{
                width: 6, height: 6, borderRadius: '50%',
                background: '#8696A0',
                animation: `wa-dot 1.1s ${i * 0.15}s infinite ease-in-out`,
              }}/>
            ))}
          </div>
        )}
      </div>
      <WAInputBar />
    </div>
  );
}

function WhatsAppPhone({ kind, dark = false }) {
  return (
    <div style={{
      transform: 'scale(0.86)',
      transformOrigin: 'top right',
      marginLeft: 'auto',
      width: 'fit-content',
    }}>
      <IOSDevice width={380} height={800} dark={dark}>
        <WAScreen kind={kind} />
      </IOSDevice>
    </div>
  );
}

function WAMount() {
  const [kind, setKind] = React.useState(() => window.__reeflyDemo || 'celular');

  React.useEffect(() => {
    const handler = (e) => {
      if (e.detail && e.detail.demo) setKind(e.detail.demo);
    };
    window.addEventListener('reefly:demo', handler);
    return () => window.removeEventListener('reefly:demo', handler);
  }, []);

  return <WhatsAppPhone kind={kind} />;
}

window.WAMount = WAMount;
window.mountWA = function(el, kind) {
  if (!el) return;
  if (el.__waRoot) el.__waRoot.unmount();
  const root = ReactDOM.createRoot(el);
  el.__waRoot = root;
  root.render(<WAMount />);
};
