// bot-ui.jsx — Componentes visuales del chat de WhatsApp para el bot CobraNow.
// Exporta: WAHead, WAMessage, WATyping, WAPill, WAComposer, WACelebration, waFormat

// *negritas* y _cursivas_ estilo WhatsApp
function waFormat(text) {
  const parts = [];
  let rest = text, k = 0;
  const re = /(\*[^*\n]+\*|_[^_\n]+_)/;
  while (rest.length) {
    const m = rest.match(re);
    if (!m) { parts.push(rest); break; }
    if (m.index > 0) parts.push(rest.slice(0, m.index));
    const tok = m[0];
    if (tok.startsWith('*')) parts.push(<b key={k++}>{tok.slice(1, -1)}</b>);
    else parts.push(<i key={k++} style={{ opacity: 0.85 }}>{tok.slice(1, -1)}</i>);
    rest = rest.slice(m.index + tok.length);
  }
  return parts;
}

function WAHead({ dark }) {
  return (
    <div className="wa-head">
      <svg width="9" height="16" viewBox="0 0 9 16" fill="none"><path d="M8 1L1.5 8L8 15" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
      <div className="av"><img src="assets/cobranow-mark.png" alt="" /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="nm">
          CobraNow
          <svg width="14" height="14" viewBox="0 0 16 16"><circle cx="8" cy="8" r="8" fill="#25D366"/><path d="M4.6 8.4l2.2 2.2 4.4-4.8" stroke="#fff" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </div>
        <div className="st">Cuenta de empresa · en línea</div>
      </div>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" opacity="0.85"><path d="M20 15.5c-1.2 0-2.5-.2-3.6-.6h-.3c-.3 0-.5.1-.7.3l-2.2 2.2c-2.8-1.5-5.2-3.8-6.6-6.6l2.2-2.2c.3-.3.4-.7.2-1-.3-1.1-.5-2.4-.5-3.6 0-.6-.4-1-1-1H4c-.6 0-1 .4-1 1 0 9.4 7.6 17 17 17 .6 0 1-.4 1-1v-3.5c0-.6-.4-1-1-1z"/></svg>
    </div>
  );
}

function WAPill({ children }) {
  return <div className="wa-pill">{children}</div>;
}

function WATyping() {
  return (
    <div className="wa-msg in wa-msg-enter">
      <div className="wa-bubble wa-typing"><span></span><span></span><span></span></div>
    </div>
  );
}

// ── contenidos especiales ──
function FwdContent({ msg }) {
  return (
    <div>
      <div className="wa-fwd-tag">
        <svg width="12" height="12" viewBox="0 0 16 16" fill="currentColor"><path d="M9 3v3C4 6.5 1.8 9.8 1 13c2-2.2 4.5-3.3 8-3.3V13l6-5-6-5z"/></svg>
        Reenviado
      </div>
      <div style={{ borderLeft: '3px solid #a791e0', borderRadius: 3, padding: '4px 8px', background: 'rgba(0,0,0,0.045)', marginBottom: 4 }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: '#7B5FC0' }}>{msg.fromName}</div>
        <div style={{ fontSize: 13 }}>{msg.text}</div>
      </div>
      <span className="wa-time">{msg.time}</span>
    </div>
  );
}

function ScreenshotContent({ msg }) {
  const B = ({ out, w, children }) => (
    <div style={{
      alignSelf: out ? 'flex-end' : 'flex-start',
      background: out ? '#d3f5cb' : '#fff',
      borderRadius: 6, padding: '3px 6px', fontSize: 7.5, color: '#333',
      width: w, boxShadow: '0 0.5px 1px rgba(0,0,0,0.1)',
    }}>{children}</div>
  );
  return (
    <div>
      <div className="wa-img-frame" style={{ width: 196 }}>
        <div style={{ background: '#EFE7DC', padding: 8, display: 'flex', flexDirection: 'column', gap: 4 }}>
          <div style={{ background: '#075E54', margin: -8, marginBottom: 2, padding: '6px 8px', display: 'flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 14, height: 14, borderRadius: 99, background: '#F8BBD0', fontSize: 7, fontWeight: 700, color: '#AD1457', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>S</span>
            <span style={{ fontSize: 8.5, fontWeight: 600, color: '#fff' }}>Sofía ✨</span>
          </div>
          <B>Holaa vi la blusa bordada 😍 ¿me la apartas?</B>
          <B out>¡Claro! Son $350 ¿te la guardo?</B>
          <B>Síí porfa, te pago el sábado que cobro 🙏</B>
          <B out>Va, apartada ✨</B>
        </div>
      </div>
      <span className="wa-time">{msg.time}</span>
    </div>
  );
}

function AudioContent({ msg }) {
  const bars = [5, 9, 14, 8, 16, 11, 18, 7, 13, 17, 9, 14, 6, 11, 16, 8, 12, 5, 9, 13, 7, 10];
  return (
    <div>
      <div className="wa-audio">
        <div className="mic">
          C
          <svg width="13" height="13" viewBox="0 0 16 16"><circle cx="8" cy="8" r="8" fill="#25D366"/><path d="M8 4a1.4 1.4 0 0 0-1.4 1.4v2.2a1.4 1.4 0 1 0 2.8 0V5.4A1.4 1.4 0 0 0 8 4zm-3 3.6h1a2 2 0 0 0 4 0h1a3 3 0 0 1-2.5 2.95V12h-1v-1.45A3 3 0 0 1 5 7.6z" fill="#fff"/></svg>
        </div>
        <div className="play">
          <svg width="15" height="17" viewBox="0 0 15 17"><path d="M1 1.5v14l13-7-13-7z" fill="currentColor" opacity="0.6"/></svg>
        </div>
        <div className="wave">
          {bars.map((h, i) => <i key={i} style={{ height: h }}></i>)}
        </div>
        <span style={{ fontSize: 11, color: 'var(--wab-ink-2)', flexShrink: 0 }}>{msg.duration}</span>
      </div>
      <div className="wa-transcript">{msg.transcript}</div>
      <span className="wa-time">{msg.time}</span>
    </div>
  );
}

function ReceiptContent({ msg }) {
  const r = msg.receipt || { name: 'María G.', concept: '2 vestidos · catálogo', amount: '$1,450', date: '9 jun 2026 · 20:14', file: 'Recibo_Maria_1450.pdf', size: '28 kB' };
  return (
    <div>
      {/* documento PDF — como lo muestra WhatsApp: miniatura de la página + barra de archivo */}
      <div className="wa-img-frame" style={{ width: 240, background: '#fff' }}>
        {/* miniatura de la primera página del PDF */}
        <div style={{ background: '#e9eef2', padding: '12px 12px 0' }}>
          <div style={{ background: '#fff', boxShadow: '0 1px 4px rgba(0,0,0,0.16)', padding: '14px 14px 16px', borderTopLeftRadius: 2, borderTopRightRadius: 2 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, paddingBottom: 9, borderBottom: '1px solid #eee' }}>
              <img src="assets/cobranow-mark.png" alt="" style={{ width: 22, height: 22, objectFit: 'contain' }} />
              <div style={{ lineHeight: 1.1 }}>
                <div style={{ fontSize: 11, fontWeight: 800, color: '#111', letterSpacing: '-0.01em' }}>Recibo de pago</div>
                <div style={{ fontSize: 7.5, color: '#aeaeb2', letterSpacing: '0.04em' }}>COMPROBANTE NO FISCAL</div>
              </div>
            </div>
            <div style={{ padding: '10px 0', display: 'flex', flexDirection: 'column', gap: 6 }}>
              {[['Recibido de', r.name], ['Concepto', r.concept], ['Fecha', r.date]].map(([l, v]) => (
                <div key={l} style={{ display: 'flex', justifyContent: 'space-between', gap: 10, fontSize: 8.5 }}>
                  <span style={{ color: '#9aa0a6' }}>{l}</span>
                  <span style={{ color: '#222', fontWeight: 600, textAlign: 'right' }}>{v}</span>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', borderTop: '1px solid #eee', paddingTop: 8 }}>
              <span style={{ fontSize: 9, color: '#9aa0a6', fontWeight: 600 }}>TOTAL PAGADO</span>
              <b style={{ fontSize: 17, color: '#111', letterSpacing: '-0.02em' }}>{r.amount}</b>
            </div>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, marginTop: 10, fontSize: 8, fontWeight: 800, color: '#1d7a32', border: '1.5px solid #1d7a32', borderRadius: 4, padding: '3px 7px', letterSpacing: '0.06em', transform: 'rotate(-3deg)' }}>
              <svg width="9" height="9" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="7" stroke="currentColor" strokeWidth="2"/><path d="M5 8.2l2 2 4-4.4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
              PAGADO
            </div>
          </div>
        </div>
        {/* barra de archivo PDF nativa de WhatsApp */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', background: '#f5f6f6' }}>
          <svg width="28" height="28" viewBox="0 0 30 30" style={{ flexShrink: 0 }}>
            <rect x="4" y="2" width="22" height="26" rx="3" fill="#E2554D"/>
            <path d="M19 2v6h7" fill="#F08B85"/>
            <text x="15" y="21" textAnchor="middle" fontSize="7.5" fontWeight="800" fill="#fff" fontFamily="-apple-system, sans-serif">PDF</text>
          </svg>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12, fontWeight: 500, color: '#111b21', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.file}</div>
            <div style={{ fontSize: 10, color: '#667781' }}>1 página · PDF · {r.size}</div>
          </div>
          <svg width="24" height="24" viewBox="0 0 26 26" style={{ flexShrink: 0 }}>
            <circle cx="13" cy="13" r="12" fill="none" stroke="#8696a0" strokeWidth="1.4"/>
            <path d="M13 7.5v8M9.5 12.5l3.5 3.5 3.5-3.5" stroke="#8696a0" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
      </div>
      <span className="wa-time">{msg.time}</span>
    </div>
  );
}

function ChartContent({ msg }) {
  const days = [
    { d: 'L', v: 38 }, { d: 'M', v: 62 }, { d: 'M', v: 20 }, { d: 'J', v: 48 },
    { d: 'V', v: 88 }, { d: 'S', v: 56 }, { d: 'D', v: 0 },
  ];
  return (
    <div>
      <div className="wa-img-frame" style={{ width: 238 }}>
        <div style={{ background: '#0e1f14', padding: '14px 16px 10px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
            <img src="assets/cobranow-mark.png" alt="" style={{ width: 16, height: 16, objectFit: 'contain' }} />
            <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '0.08em', color: '#7fbf8e' }}>TU SEMANA</span>
          </div>
          <div style={{ fontSize: 22, fontWeight: 800, color: '#fff', letterSpacing: '-0.02em' }}>$4,300 <span style={{ fontSize: 11, fontWeight: 600, color: '#5fd882' }}>▲ 18%</span></div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 7, height: 64, marginTop: 10 }}>
            {days.map((x, i) => (
              <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                <div style={{
                  width: '100%', height: Math.max(3, x.v * 0.6),
                  borderRadius: 4,
                  background: x.v >= 88 ? '#5fd882' : 'rgba(95,216,130,0.32)',
                }}></div>
                <span style={{ fontSize: 8.5, color: '#7fbf8e' }}>{x.d}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
      <span className="wa-time">{msg.time}</span>
    </div>
  );
}

// ── mensaje genérico ──
function WAMessage({ msg, onButton, name }) {
  const isUser = msg.from === 'user';
  let content;
  if (msg.kind === 'forward') content = <FwdContent msg={msg} />;
  else if (msg.kind === 'screenshot') content = <ScreenshotContent msg={msg} />;
  else if (msg.kind === 'audio') content = <AudioContent msg={msg} />;
  else if (msg.kind === 'receipt') content = <ReceiptContent msg={msg} />;
  else if (msg.kind === 'chart') content = <ChartContent msg={msg} />;
  else content = (
    <div>
      {waFormat((msg.text || '').split('{name}').join(name))}
      <span className="wa-time">{msg.time}{isUser && <span style={{ color: '#53bdeb' }}> ✓✓</span>}</span>
    </div>
  );
  return (
    <div className={`wa-msg ${isUser ? 'out' : 'in'} wa-msg-enter`}>
      <div className="wa-bubble">{content}</div>
      {msg.buttons && (
        <div className="wa-replies">
          {msg.buttons.map((b) => (
            <button
              key={b.label}
              className={`wa-reply-btn ${msg.chosen === b.label ? 'chosen' : ''}`}
              disabled={!!msg.chosen}
              onClick={() => onButton(msg, b)}
            >{b.label}</button>
          ))}
        </div>
      )}
    </div>
  );
}

function WAComposer({ chip, onChip, locked }) {
  return (
    <div className="wa-composer-zone">
      {chip && !locked && (
        <div className="wa-chips">
          <span className="wa-chips-label">Simula tu siguiente paso</span>
          <button className="wa-chip-btn" onClick={onChip}>
            <span>{chip.icon}</span> {chip.label}
          </button>
        </div>
      )}
      <div className="wa-composer">
        <span className="wa-icon-btn">
          <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z"/></svg>
        </span>
        <div className="wa-input">Mensaje</div>
        <span className="wa-icon-btn">
          <svg width="21" height="21" viewBox="0 0 24 24" fill="currentColor"><path d="M12 9a3.2 3.2 0 1 0 0 6.4A3.2 3.2 0 0 0 12 9zm8-3h-2.6l-1.8-2H8.4L6.6 6H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2zm-8 11.2a5 5 0 1 1 0-10 5 5 0 0 1 0 10z"/></svg>
        </span>
        <span className="wa-icon-btn" style={{ background: 'var(--green)', borderRadius: 999, width: 38, height: 38, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 14a3 3 0 0 0 3-3V5a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3zm5-3a5 5 0 0 1-10 0H5a7 7 0 0 0 6 6.92V21h2v-3.08A7 7 0 0 0 19 11h-2z"/></svg>
        </span>
      </div>
    </div>
  );
}

function WACelebration({ trigger }) {
  const [items, setItems] = React.useState([]);
  React.useEffect(() => {
    if (!trigger) return;
    const glyphs = ['💸', '💚', '✨', '🎉', '🐍', '💵'];
    const arr = Array.from({ length: 16 }, (_, i) => ({
      id: trigger + '-' + i,
      g: glyphs[i % glyphs.length],
      left: 5 + Math.random() * 90,
      delay: Math.random() * 0.5,
      dur: 1.3 + Math.random() * 0.9,
    }));
    setItems(arr);
    const t = setTimeout(() => setItems([]), 2800);
    return () => clearTimeout(t);
  }, [trigger]);
  if (!items.length) return null;
  return (
    <div className="wa-celebrate">
      {items.map((c) => (
        <i key={c.id} style={{ left: c.left + '%', animationDelay: c.delay + 's', animationDuration: c.dur + 's' }}>{c.g}</i>
      ))}
    </div>
  );
}

Object.assign(window, { WAHead, WAMessage, WATyping, WAPill, WAComposer, WACelebration, waFormat });
