// AGENTFORGE-IA — Agente de voz + chat de soporte (disponible en toda la app)

// Limpia el texto de un mensaje antes de mostrarlo
const _cleanMsg = (raw) => {
  if (!raw) return '';
  // Quita el token BOOKING
  let s = raw.replace(/\s*BOOKING:\{[^}]*\}/g, '').trim();
  // Si lo que queda es JSON puro, lo descartamos o simplificamos
  if (s.startsWith('{') && s.endsWith('}')) {
    try {
      const obj = JSON.parse(s);
      const note = obj.note || obj.message || obj.mode_name || obj.source || '';
      return note ? String(note) : '';
    } catch (_) { return ''; }
  }
  return s;
};

// Web Speech API helpers
const _SR = window.SpeechRecognition || window.webkitSpeechRecognition || null;
const _SS = window.speechSynthesis || null;

// Selecciona la voz más natural disponible: prioriza voces neurales/online
const _pickVoice = (lang) => {
  const voices = _SS ? _SS.getVoices() : [];
  const langCode = lang.substring(0, 2);
  const candidates = voices.filter(v => v.lang.startsWith(langCode));
  // 1. Voz online/neural (Google, Microsoft Neural) — la más humana
  const online = candidates.find(v => !v.localService && (
    v.name.includes('Google') || v.name.includes('Neural') || v.name.includes('Online')
  ));
  if (online) return online;
  // 2. Cualquier voz online del idioma
  const anyOnline = candidates.find(v => !v.localService);
  if (anyOnline) return anyOnline;
  // 3. Voz local del idioma como último recurso
  return candidates[0] || null;
};

const _speak = (text, lang = 'es-ES') => {
  if (!_SS) return;
  _SS.cancel();
  const utt = new SpeechSynthesisUtterance(text);
  utt.lang = lang;
  utt.rate = 0.91;   // ligeramente más lento = más natural
  utt.pitch = 0.93;  // tono algo más suave y cálido
  utt.volume = 1;
  // Las voces pueden no estar listas en el primer render; intentamos en onvoiceschanged si es necesario
  const voice = _pickVoice(lang);
  if (voice) utt.voice = voice;
  else if (_SS.onvoiceschanged !== undefined) {
    _SS.onvoiceschanged = () => { const v = _pickVoice(lang); if (v) utt.voice = v; };
  }
  _SS.speak(utt);
};

const SupportChat = ({ currentUser, overlayOpen = false }) => {
  if (currentUser?.is_admin) return null;
  const [uiLang, setUiLang] = React.useState(() => {
    try { return localStorage.getItem('af_ui_lang') || window.afUiLang || 'es'; } catch { return 'es'; }
  });
  const [open, setOpen] = React.useState(false);
  const [mode, setMode] = React.useState('chat'); // 'chat' | 'voice'
  const [forcePublicForm, setForcePublicForm] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [messages, setMessages] = React.useState([]);
  const [text, setText] = React.useState('');
  const [listening, setListening] = React.useState(false);
  const [voiceStatus, setVoiceStatus] = React.useState(''); // 'listening' | 'processing' | 'speaking' | ''
  const [bookingWidget, setBookingWidget] = React.useState(null);
  const [bookingForm, setBookingForm] = React.useState({ meeting_type: 'demo', preferred_date: '', preferred_time: '10:00', message: '' });
  const [bookingStatus, setBookingStatus] = React.useState('');
  const [userInfo, setUserInfo] = React.useState({ name: '', email: '' });
  const [publicForm, setPublicForm] = React.useState({
    full_name: '', email: '', reason: '', company: '', preferred_datetime: '', message: '',
  });
  const srRef = React.useRef(null);
  const bodyRef = React.useRef(null);
  const token = sessionStorage.getItem('af_token') || '';
  const canUse = !!currentUser && !forcePublicForm;
  const srAvailable = !!_SR;
  const tomorrowStr = () => { const d = new Date(); d.setDate(d.getDate() + 1); return d.toISOString().slice(0, 10); };
  const openBooking = (bd) => {
    setBookingWidget(bd);
    setBookingForm({ meeting_type: bd.meeting_type || 'demo', preferred_date: tomorrowStr(), preferred_time: '10:00', message: bd.reason || bd.message || '' });
    setBookingStatus('');
  };

  const scrollBottom = () => {
    setTimeout(() => {
      if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
    }, 50);
  };

  const loadMessages = React.useCallback(async () => {
    if (!canUse) return;
    setMessages([]);
    setLoading(true);
    try {
      const res = await fetch('/api/v1/support/messages', {
        headers: { Authorization: 'Bearer ' + (sessionStorage.getItem('af_token') || '') },
      });
      if (!res.ok) return;
      const data = await res.json();
      const clean = (Array.isArray(data) ? data : []).filter(m => _cleanMsg(m.message));
      setMessages(clean);
      scrollBottom();
    } finally { setLoading(false); }
  }, [canUse]);

  React.useEffect(() => {
    if (!canUse || !token) return;
    let fallbackName = '', fallbackEmail = '';
    try {
      const p = JSON.parse(atob(token.split('.')[1]));
      fallbackEmail = p.sub || p.email || '';
      if (fallbackEmail.includes('@')) {
        const raw = fallbackEmail.split('@')[0];
        fallbackName = raw.charAt(0).toUpperCase() + raw.slice(1).replace(/[._-]/g, ' ');
      }
    } catch (_) {}
    fetch('/api/v1/customers/me', { headers: { Authorization: 'Bearer ' + token } })
      .then(r => r.ok ? r.json() : null)
      .then(me => setUserInfo({ name: ((me?.full_name || me?.fullName || fallbackName) + '').trim(), email: me?.email || fallbackEmail }))
      .catch(() => setUserInfo({ name: fallbackName, email: fallbackEmail }));
  }, [canUse, token]);

  React.useEffect(() => { if (open) setMessages([]); }, [open]);
  React.useEffect(() => {
    const h = (e) => { setForcePublicForm(!!e?.detail?.public); setOpen(true); };
    window.addEventListener('af:contact:open', h);
    return () => window.removeEventListener('af:contact:open', h);
  }, []);
  React.useEffect(() => { if (overlayOpen && open) setOpen(false); }, [overlayOpen, open]);
  React.useEffect(() => {
    const h = (e) => setUiLang((e && e.detail) || window.afUiLang || 'es');
    window.addEventListener('af:lang', h);
    return () => window.removeEventListener('af:lang', h);
  }, []);

  // Stop voice when closing
  React.useEffect(() => {
    if (!open) { srRef.current?.abort(); _SS?.cancel(); setListening(false); setVoiceStatus(''); }
  }, [open]);

  const sendText = async (msg) => {
    const clean = msg.trim();
    if (!clean || !canUse) return;
    setText('');
    setLoading(true);
    if (mode === 'voice') setVoiceStatus('processing');
    try {
      const res = await fetch('/api/v1/support/messages', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + (sessionStorage.getItem('af_token') || '') },
        body: JSON.stringify({ message: clean }),
      });
      if (!res.ok) return;
      const data = await res.json();
      const msgs = (Array.isArray(data) ? data : []).filter(m => _cleanMsg(m.message));
      setMessages(msgs);
      scrollBottom();

      const last = msgs[msgs.length - 1];
      if (last && last.role === 'support') {
        const visibleText = _cleanMsg(last.message);
        // Voz: leer respuesta en voz alta
        if (mode === 'voice' && visibleText) {
          setVoiceStatus('speaking');
          _speak(visibleText, uiLang === 'en' ? 'en-US' : 'es-ES');
          if (_SS) {
            const check = setInterval(() => {
              if (!_SS.speaking) { setVoiceStatus(''); clearInterval(check); }
            }, 300);
          } else { setVoiceStatus(''); }
        }
        // Booking intent — abre widget inline en el chat
        if (last.message.includes('BOOKING:')) {
          try {
            const match = last.message.match(/BOOKING:(\{[^}]+\})/);
            openBooking(match ? JSON.parse(match[1]) : {});
          } catch (_) {}
        }
      }
    } finally { setLoading(false); if (mode !== 'voice') setVoiceStatus(''); }
  };

  const send = () => sendText(text);

  const submitBooking = async () => {
    setBookingStatus('submitting');
    try {
      const res = await fetch('/api/v1/booking/public', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          full_name: userInfo.name, email: userInfo.email,
          meeting_type: bookingForm.meeting_type,
          preferred_date: bookingForm.preferred_date,
          preferred_time: bookingForm.preferred_time,
          timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'Europe/Madrid',
          duration_minutes: { demo: 30, discovery: 30, support: 60, consulting: 60, qbr: 90, other: 30 }[bookingForm.meeting_type] || 30,
          message: bookingForm.message || '',
        }),
      });
      if (!res.ok) throw new Error();
      setBookingStatus('done');
      setTimeout(() => { setBookingWidget(null); setBookingStatus(''); }, 4000);
    } catch (_) { setBookingStatus('error'); }
  };

  // Iniciar/detener escucha de voz
  const toggleListen = () => {
    if (!_SR) return;
    if (listening) {
      srRef.current?.stop();
      setListening(false);
      setVoiceStatus('');
      return;
    }
    const sr = new _SR();
    srRef.current = sr;
    sr.lang = uiLang === 'en' ? 'en-US' : 'es-ES';
    sr.interimResults = false;
    sr.maxAlternatives = 1;
    sr.onstart = () => { setListening(true); setVoiceStatus('listening'); };
    sr.onresult = (e) => {
      const transcript = e.results[0][0].transcript;
      setListening(false);
      sendText(transcript);
    };
    sr.onerror = () => { setListening(false); setVoiceStatus(''); };
    sr.onend = () => { setListening(false); };
    sr.start();
  };

  const sendPublicContact = async () => {
    const payload = {
      full_name: publicForm.full_name.trim(), email: publicForm.email.trim(),
      reason: publicForm.reason.trim(), company: publicForm.company.trim(),
      preferred_datetime: publicForm.preferred_datetime.trim(), message: publicForm.message.trim(),
    };
    if (!payload.full_name || !payload.email || !payload.reason || !payload.message) return;
    setLoading(true);
    try {
      const res = await fetch('/api/v1/support/public-contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!res.ok) return;
      setPublicForm({ full_name: '', email: '', reason: '', company: '', preferred_datetime: '', message: '' });
      window.afNotify && window.afNotify('Solicitud enviada. Te contactaremos por email.');
      setOpen(false);
    } finally { setLoading(false); }
  };

  const voiceStatusLabel = { listening: '🎙 Escuchando…', processing: '⏳ Procesando…', speaking: '🔊 Respondiendo…' };

  return (
    <>
      {!overlayOpen && (
        <div style={{ position: 'fixed', right: 16, bottom: 16, zIndex: 70, display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8 }}>
          <button
            className="btn btn-primary"
            onClick={() => { setMode('chat'); setOpen(true); }}
            style={{ borderRadius: 999, gap: 6, background: 'var(--brand)', boxShadow: '0 4px 16px rgba(0,0,0,0.25)' }}
            title={uiLang === 'en' ? 'Contact AgentForge' : 'Contacta con AgentForge'}
          >
            <Icon name="chat" size={14} />
            {uiLang === 'en' ? 'Contact AgentForge' : 'Contacta con AgentForge'}
          </button>
          <button
            className="btn"
            onClick={() => { setMode('chat'); setOpen((v) => !v); }}
            style={{ borderRadius: 999, gap: 6, fontSize: 12, padding: '6px 12px' }}
            title={uiLang === 'en' ? 'Chat support' : 'Chat de soporte'}
          >
            <Icon name="chat" size={13} />
          </button>
        </div>
      )}

      {open && !overlayOpen && (
        <div style={{
          position: 'fixed', right: 16, bottom: 64,
          width: 360, maxWidth: 'calc(100vw - 24px)',
          height: mode === 'voice' && canUse ? 400 : 480,
          zIndex: 71, background: 'var(--bg-1)',
          border: '1px solid var(--line-2)', borderRadius: 12,
          boxShadow: 'var(--shadow-pop)', display: 'flex',
          flexDirection: 'column', overflow: 'hidden',
          transition: 'height 0.2s',
        }}>
          {/* Header */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', borderBottom: '1px solid var(--line)', flexShrink: 0 }}>
            <Icon name={mode === 'voice' ? 'mic' : 'headset'} size={14} />
            <b style={{ fontSize: 13 }}>Soporte AgentForge</b>
            <span className="status-dot live" style={{ marginLeft: 'auto' }} />
            {/* Selector de modo voz/chat */}
            {canUse && (
              <div style={{ display: 'flex', background: 'var(--bg-3)', borderRadius: 6, padding: 2, gap: 1 }}>
                <button
                  onClick={() => { setMessages([]); setMode('chat'); _SS?.cancel(); setVoiceStatus(''); }}
                  style={{ padding: '2px 9px', borderRadius: 4, border: 'none', cursor: 'pointer', fontSize: 11, fontWeight: 600, fontFamily: 'inherit', background: mode === 'chat' ? 'var(--bg-1)' : 'transparent', color: mode === 'chat' ? 'var(--ink)' : 'var(--ink-3)', boxShadow: mode === 'chat' ? 'var(--shadow-1)' : 'none' }}
                >Chat</button>
                <button
                  onClick={() => { setMessages([]); setMode('voice'); }}
                  style={{ padding: '2px 9px', borderRadius: 4, border: 'none', cursor: 'pointer', fontSize: 11, fontWeight: 600, fontFamily: 'inherit', background: mode === 'voice' ? 'var(--bg-1)' : 'transparent', color: mode === 'voice' ? 'var(--brand)' : 'var(--ink-3)', boxShadow: mode === 'voice' ? 'var(--shadow-1)' : 'none' }}
                >Voz</button>
              </div>
            )}
            <button className="btn btn-ghost btn-icon btn-sm" onClick={() => setOpen(false)}><Icon name="x" size={13} /></button>
          </div>

          {/* Modo VOZ */}
          {canUse && mode === 'voice' && (
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 16, padding: 20 }}>
              {/* Orb de voz */}
              <div
                onClick={toggleListen}
                style={{
                  width: 96, height: 96, borderRadius: '50%',
                  background: listening
                    ? 'radial-gradient(circle, rgba(255,91,31,0.9) 0%, rgba(255,91,31,0.4) 70%)'
                    : voiceStatus === 'speaking'
                      ? 'radial-gradient(circle, rgba(52,211,153,0.9) 0%, rgba(52,211,153,0.3) 70%)'
                      : 'var(--bg-3)',
                  border: '2px solid ' + (listening ? 'var(--brand)' : voiceStatus === 'speaking' ? '#34d399' : 'var(--line-2)'),
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  cursor: srAvailable ? 'pointer' : 'not-allowed',
                  boxShadow: listening ? '0 0 28px rgba(255,91,31,0.5)' : voiceStatus === 'speaking' ? '0 0 24px rgba(52,211,153,0.4)' : 'none',
                  transition: 'all 0.3s',
                  animation: listening ? 'pulse 1.2s infinite' : 'none',
                }}
              >
                <Icon name={listening ? 'mic' : voiceStatus === 'speaking' ? 'volume-2' : 'mic'} size={36} style={{ color: listening ? '#fff' : voiceStatus === 'speaking' ? '#34d399' : 'var(--ink-3)' }} />
              </div>

              <div style={{ fontSize: 13, color: 'var(--ink-3)', textAlign: 'center', minHeight: 20 }}>
                {voiceStatus ? voiceStatusLabel[voiceStatus] : srAvailable ? (uiLang === 'en' ? 'Tap to speak' : 'Pulsa para hablar') : 'Voz no disponible en este navegador'}
              </div>

              {!srAvailable && (
                <div style={{ fontSize: 11.5, color: 'var(--ink-4)', textAlign: 'center' }}>
                  Usa Chrome o Edge para activar el micrófono.
                </div>
              )}

              {/* Historial compacto */}
              {messages.length > 0 && (
                <div ref={bodyRef} style={{ width: '100%', maxHeight: 120, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {messages.slice(-4).map((m) => {
                    const txt = _cleanMsg(m.message);
                    if (!txt) return null;
                    return (
                      <div key={m.id} style={{ fontSize: 11.5, color: m.role === 'user' ? 'var(--ink-2)' : 'var(--ink)', background: m.role === 'user' ? 'var(--bg-3)' : 'var(--brand-soft)', borderRadius: 6, padding: '4px 8px', alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start', maxWidth: '90%' }}>
                        {txt}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          )}

          {/* Modo CHAT — mensajes */}
          {canUse && mode === 'chat' && (
            <div ref={bodyRef} style={{ flex: 1, overflowY: 'auto', padding: 12, display: 'flex', flexDirection: 'column', gap: 10 }}>
              {messages.length === 0 && !loading && (
                <div style={{ color: 'var(--ink-3)', fontSize: 12.5, textAlign: 'center', marginTop: 20 }}>
                  Hola 👋 ¿En qué puedo ayudarte?
                </div>
              )}
              {messages.map((m) => {
                const txt = _cleanMsg(m.message);
                if (!txt) return null;
                return (
                  <div key={m.id} style={{ alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start', maxWidth: '88%' }}>
                    <div style={{
                      background: m.role === 'user' ? 'var(--brand)' : 'var(--bg-2)',
                      color: m.role === 'user' ? '#fff' : 'var(--ink)',
                      border: '1px solid var(--line)',
                      borderRadius: m.role === 'user' ? '10px 10px 2px 10px' : '10px 10px 10px 2px',
                      padding: '8px 10px',
                      whiteSpace: 'pre-wrap', wordBreak: 'break-word',
                      fontSize: 12.5, lineHeight: 1.45,
                    }}>
                      {txt}
                      {m.role === 'support' && m.message.includes('BOOKING:') && (
                        <div style={{ marginTop: 6 }}>
                          <button
                            onClick={() => { try { const match = m.message.match(/BOOKING:(\{[^}]+\})/); openBooking(match ? JSON.parse(match[1]) : {}); } catch(_){} }}
                            style={{ background: 'none', border: 'none', color: 'var(--brand)', fontSize: 11.5, fontWeight: 600, cursor: 'pointer', padding: 0 }}
                          >📅 Ver disponibilidad →</button>
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
              {/* ── Widget de reserva inline ── */}
              {bookingWidget && (
                <div style={{ alignSelf: 'flex-start', width: '100%' }}>
                  <div style={{ background: 'var(--bg-2)', border: '1px solid color-mix(in oklab, var(--brand) 30%, var(--line-2))', borderRadius: 10, padding: 14, display: 'grid', gap: 10 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--brand)' }}>📅 Reservar cita</div>
                    {bookingStatus === 'done' ? (
                      <div style={{ color: 'var(--ok)', fontSize: 12.5, textAlign: 'center', padding: '10px 0' }}>
                        ✅ ¡Solicitud enviada! Te confirmaremos en <b>{userInfo.email}</b>.
                      </div>
                    ) : (
                      <>
                        <div style={{ fontSize: 11.5, color: 'var(--ink-3)', background: 'var(--bg-3)', borderRadius: 6, padding: '6px 10px' }}>
                          <b style={{ color: 'var(--ink)' }}>{userInfo.name}</b>{userInfo.email ? ` · ${userInfo.email}` : ''}
                        </div>
                        <select className="input" style={{ fontSize: 12.5, padding: '6px 10px' }}
                          value={bookingForm.meeting_type}
                          onChange={e => setBookingForm(p => ({ ...p, meeting_type: e.target.value }))}>
                          {[['demo','Demo de producto'],['discovery','Llamada de descubrimiento'],['support','Soporte técnico'],['consulting','Consultoría'],['other','Reunión general']].map(([v,l]) => (
                            <option key={v} value={v}>{l}</option>
                          ))}
                        </select>
                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                          <input className="input" type="date" style={{ fontSize: 12.5, padding: '6px 10px' }}
                            value={bookingForm.preferred_date} min={tomorrowStr()}
                            onChange={e => setBookingForm(p => ({ ...p, preferred_date: e.target.value }))} />
                          <input className="input" type="time" style={{ fontSize: 12.5, padding: '6px 10px' }}
                            value={bookingForm.preferred_time}
                            onChange={e => setBookingForm(p => ({ ...p, preferred_time: e.target.value }))} />
                        </div>
                        <textarea className="textarea" rows={2} placeholder="Motivo o comentario…" style={{ fontSize: 12.5, resize: 'none' }}
                          value={bookingForm.message}
                          onChange={e => setBookingForm(p => ({ ...p, message: e.target.value }))} />
                        {bookingStatus === 'error' && (
                          <div style={{ color: 'var(--bad)', fontSize: 11.5 }}>Error al enviar. Inténtalo de nuevo.</div>
                        )}
                        <div style={{ display: 'flex', gap: 6 }}>
                          <button className="btn btn-sm btn-primary" style={{ flex: 1 }}
                            onClick={submitBooking}
                            disabled={bookingStatus === 'submitting' || !bookingForm.preferred_date}>
                            {bookingStatus === 'submitting' ? 'Enviando…' : 'Confirmar cita'}
                          </button>
                          <button className="btn btn-sm" onClick={() => { setBookingWidget(null); setBookingStatus(''); }}>
                            Cancelar
                          </button>
                        </div>
                      </>
                    )}
                  </div>
                </div>
              )}
              {loading && <div className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', alignSelf: 'flex-start' }}>Procesando…</div>}
            </div>
          )}

          {/* Formulario público */}
          {!canUse && (
            <div style={{ flex: 1, overflowY: 'auto', padding: 12, display: 'grid', gap: 8 }}>
              <p style={{ color: 'var(--ink-3)', fontSize: 12.5, margin: 0 }}>Envíanos tu consulta y te respondemos desde agentforge@agentforge-ia.pro.</p>
              <input className="input" placeholder="Nombre y apellidos *" value={publicForm.full_name} onChange={(e) => setPublicForm((p) => ({ ...p, full_name: e.target.value }))} />
              <input className="input" placeholder="Email de contacto *" value={publicForm.email} onChange={(e) => setPublicForm((p) => ({ ...p, email: e.target.value }))} />
              <input className="input" placeholder="Motivo del contacto *" value={publicForm.reason} onChange={(e) => setPublicForm((p) => ({ ...p, reason: e.target.value }))} />
              <input className="input" placeholder="Empresa (opcional)" value={publicForm.company} onChange={(e) => setPublicForm((p) => ({ ...p, company: e.target.value }))} />
              <input className="input" placeholder="Fecha/hora preferida (opcional)" value={publicForm.preferred_datetime} onChange={(e) => setPublicForm((p) => ({ ...p, preferred_datetime: e.target.value }))} />
              <textarea className="textarea" rows={3} placeholder="Cuéntanos tu duda… *" value={publicForm.message} onChange={(e) => setPublicForm((p) => ({ ...p, message: e.target.value }))} />
            </div>
          )}

          {/* Footer */}
          <div style={{ borderTop: '1px solid var(--line)', padding: '8px 10px', flexShrink: 0 }}>
            {canUse && mode === 'chat' && (
              <div style={{ display: 'flex', gap: 6, alignItems: 'flex-end' }}>
                <textarea
                  className="textarea"
                  rows={2}
                  placeholder={uiLang === 'en' ? 'Type your question…' : 'Escribe tu duda…'}
                  value={text}
                  onChange={(e) => setText(e.target.value)}
                  onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
                  disabled={loading}
                  style={{ flex: 1, resize: 'none' }}
                />
                {srAvailable && (
                  <button
                    onClick={toggleListen}
                    title="Hablar"
                    style={{ background: listening ? 'var(--brand)' : 'var(--bg-3)', border: '1px solid var(--line-2)', borderRadius: 8, padding: '6px 8px', cursor: 'pointer', color: listening ? '#fff' : 'var(--ink-3)', flexShrink: 0 }}
                  >
                    <Icon name="mic" size={14} />
                  </button>
                )}
                <button className="btn btn-sm btn-primary" onClick={send} disabled={loading || !text.trim()} style={{ flexShrink: 0 }}>Enviar</button>
              </div>
            )}
            {canUse && mode === 'voice' && voiceStatus === '' && (
              <div style={{ textAlign: 'center', fontSize: 11, color: 'var(--ink-4)' }}>
                {srAvailable ? 'Pulsa el orbe para hablar · respuesta en voz alta' : 'Modo voz requiere Chrome o Edge'}
              </div>
            )}
            {!canUse && (
              <button
                className="btn btn-sm btn-primary"
                style={{ width: '100%' }}
                onClick={sendPublicContact}
                disabled={loading || !publicForm.full_name.trim() || !publicForm.email.trim() || !publicForm.reason.trim() || !publicForm.message.trim()}
              >
                Enviar solicitud
              </button>
            )}
          </div>
        </div>
      )}

      <style>{`
        @keyframes pulse {
          0%, 100% { box-shadow: 0 0 16px rgba(255,91,31,0.4); }
          50% { box-shadow: 0 0 36px rgba(255,91,31,0.8); }
        }
      `}</style>
    </>
  );
};

window.SupportChat = SupportChat;
