/* ─────────────────────────────────────────────────────────────────────────
   Landing page AI assistant — floating chat widget
   Calls Gemini 2.5 Flash-Lite directly from the client (prototype)
   ───────────────────────────────────────────────────────────────────────── */

const { useState: useAIS, useRef: useAIR, useEffect: useAIE } = React;

const _ASSISTANT_SYSTEM =
  'Eres el asistente virtual de Menú Factory, la plataforma que permite a restaurantes crear ' +
  'su menú digital en 5 minutos usando inteligencia artificial.\n\n' +
  'SOBRE MENÚ FACTORY:\n' +
  '- Sube tu logo → extraemos tu paleta de colores automáticamente con IA\n' +
  '- Sube tu menú en PDF → nuestra IA (Gemini) extrae cada plato, descripción y precio\n' +
  '- En 5 pasos tienes un menú digital listo para tus mesas con QR personalizado por mesa\n' +
  '- Panel de administración: pedidos en tiempo real, control de cocina, cobro por mesa\n' +
  '- Si no tienes PDF, nuestra IA puede crear tu menú completo desde una descripción\n' +
  '- Sommelier IA para recomendaciones a comensales\n' +
  '- Integración con sistemas POS vía webhooks\n' +
  '- Sin código, sin aplicaciones que instalar\n' +
  '- Actualmente en beta gratuita\n\n' +
  'REGLAS ESTRICTAS:\n' +
  '1. RESPONDE SOLO preguntas sobre Menú Factory, restaurantes o tecnología gastronómica.\n' +
  '2. Si el usuario pregunta sobre CUALQUIER otro tema (clima, política, chistes, código, etc.), DECLINA CORTÉSMENTE diciendo que solo puedes hablar sobre Menú Factory.\n' +
  '3. Sé EXTREMADAMENTE BREVE. Usa máximo 2 oraciones y menos de 50 palabras por respuesta.\n' +
  '4. Si no sabes algo, pide que contacten a soporte.';

const _SUGGESTIONS = ['¿Cómo funciona?', '¿Qué incluye?', '¿Cuánto cuesta?'];

function LandingAIAssistant() {
  const [open, setOpen]     = useAIS(false);
  const [msgs, setMsgs]     = useAIS([]);
  const [input, setInput]   = useAIS('');
  const [busy, setBusy]     = useAIS(false);
  const [errMsg, setErrMsg] = useAIS('');
  const bottomRef           = useAIR(null);
  const inputRef            = useAIR(null);

  useAIE(() => {
    if (open && msgs.length === 0) {
      setMsgs([{
        role: 'assistant',
        content: '¡Hola! Soy el asistente de Menú Factory. ¿En qué te puedo ayudar? Puedo explicarte cómo funciona, qué incluye, o guiarte para empezar.',
      }]);
    }
    if (open) setTimeout(() => inputRef.current?.focus(), 120);
  }, [open]);

  useAIE(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [msgs, busy]);

  const sendMessage = async (text) => {
    if (!text || !text.trim() || busy) return;
    const trimmed = text.trim();
    setInput('');
    setErrMsg('');
    setMsgs(prev => [...prev, { role: 'user', content: trimmed }]);
    setBusy(true);
    try {
      // Build history from prior messages; skip any leading model turn (initial greeting)
      const history = [];
      for (const m of msgs.slice(-8)) {
        const role = m.role === 'user' ? 'user' : 'model';
        if (history.length === 0 && role === 'model') continue;
        history.push({ role, parts: [{ text: m.content }] });
      }
      const reply = await window._geminiGenerate({
        prompt: trimmed,
        systemInstruction: _ASSISTANT_SYSTEM,
        maxOutputTokens: 400,
        history,
      });
      setMsgs(prev => [...prev, { role: 'assistant', content: reply }]);
      window.MFTracker?.trackAIConversation([
        { role: 'user', content: trimmed },
        { role: 'assistant', content: reply },
      ]);
    } catch (_) {
      setErrMsg('No pude conectarme. Intenta de nuevo en un momento.');
    } finally {
      setBusy(false);
    }
  };

  const send = () => sendMessage(input);

  return (
    <>
      {/* Floating trigger */}
      <button
        onClick={() => setOpen(o => !o)}
        title="Asistente IA"
        style={{
          position: 'fixed', bottom: 28, right: 28, zIndex: 9000,
          width: 54, height: 54, borderRadius: '50%',
          background: 'var(--ink)', color: '#fff', fontSize: 20,
          boxShadow: '0 4px 24px rgba(0,0,0,0.22)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          transition: 'transform 160ms ease', border: 'none', cursor: 'pointer',
        }}
        onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.09)'; }}
        onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; }}
      >
        {open ? '×' : '✦'}
      </button>

      {/* Chat panel */}
      {open && (
        <div style={{
          position: 'fixed', bottom: 96, right: 28, zIndex: 8999,
          width: 356, maxHeight: 490,
          background: '#fff', borderRadius: 18,
          border: '1px solid rgba(0,0,0,0.08)',
          boxShadow: '0 16px 56px -20px rgba(0,0,0,0.3)',
          display: 'flex', flexDirection: 'column', overflow: 'hidden',
          animation: '_aiPanelIn 180ms cubic-bezier(.3,.7,.2,1)',
        }}>
          <style>{`
            @keyframes _aiPanelIn {
              from { opacity:0; transform:translateY(12px) scale(0.97); }
              to   { opacity:1; transform:translateY(0) scale(1); }
            }
            @keyframes _aiBlink {
              0%,80%,100% { opacity:0.15; }
              40% { opacity:1; }
            }
          `}</style>

          {/* Header */}
          <div style={{
            padding: '12px 18px', background: 'var(--ink)',
            display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0,
          }}>
            <div style={{
              width: 30, height: 30, borderRadius: '50%',
              background: 'rgba(255,255,255,0.12)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14,
            }}>✦</div>
            <div style={{ flex: 1 }}>
              <div style={{ color: '#fff', fontSize: 13, fontWeight: 500 }}>Asistente IA</div>
              <div style={{ color: 'rgba(255,255,255,0.5)', fontSize: 10 }}>Gemini 2.5 Flash-Lite · Menú Factory <span style={{ fontSize: 8, opacity: 0.7, letterSpacing: '0.08em' }}>by sinapsys</span></div>
            </div>
            <button onClick={() => setOpen(false)} style={{ color: 'rgba(255,255,255,0.6)', fontSize: 18, lineHeight: 1 }}>×</button>
          </div>

          {/* Messages */}
          <div style={{ flex: 1, overflowY: 'auto', padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
            {msgs.map((m, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start' }}>
                <div style={{
                  maxWidth: '84%', padding: '9px 13px', borderRadius: 12,
                  background: m.role === 'user' ? 'var(--ink)' : '#f4f2ed',
                  color: m.role === 'user' ? '#fff' : '#1a1a1a',
                  fontSize: 13, lineHeight: 1.52,
                  borderBottomRightRadius: m.role === 'user' ? 4 : 12,
                  borderBottomLeftRadius:  m.role === 'assistant' ? 4 : 12,
                }}>
                  {m.content}
                </div>
              </div>
            ))}

            {busy && (
              <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
                <div style={{
                  padding: '9px 14px', borderRadius: 12, borderBottomLeftRadius: 4,
                  background: '#f4f2ed', display: 'flex', gap: 3, alignItems: 'center',
                }}>
                  {[0, 200, 400].map(d => (
                    <span key={d} style={{ width: 6, height: 6, borderRadius: '50%', background: '#999', display: 'block', animation: `_aiBlink 1s infinite ${d}ms` }} />
                  ))}
                </div>
              </div>
            )}

            {errMsg && <div style={{ fontSize: 12, color: '#c0392b', textAlign: 'center' }}>{errMsg}</div>}
            <div ref={bottomRef} />
          </div>

          {/* Quick suggestions (shown only on first message) */}
          {msgs.length === 1 && !busy && (
            <div style={{ padding: '0 16px 10px', display: 'flex', gap: 6, flexWrap: 'wrap', flexShrink: 0 }}>
              {_SUGGESTIONS.map(s => (
                <button key={s} onClick={() => sendMessage(s)} style={{
                  padding: '5px 11px', borderRadius: 20,
                  border: '1px solid #ddd', background: 'transparent',
                  fontSize: 12, cursor: 'pointer', color: '#555',
                  transition: 'background 120ms',
                }}
                onMouseEnter={e => { e.currentTarget.style.background = '#f5f4f0'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}>
                  {s}
                </button>
              ))}
            </div>
          )}

          {/* Input */}
          <div style={{ padding: '10px 14px', borderTop: '1px solid #eee', display: 'flex', gap: 8, flexShrink: 0 }}>
            <input
              ref={inputRef}
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
              placeholder="Escribe tu pregunta…"
              disabled={busy}
              style={{
                flex: 1, padding: '8px 12px', borderRadius: 10,
                border: '1px solid #e0ddd8', fontSize: 13, outline: 'none',
                fontFamily: 'Inter, sans-serif', background: '#faf9f7',
              }}
            />
            <button
              onClick={send}
              disabled={busy || !input.trim()}
              style={{
                width: 38, height: 38, borderRadius: 10, flexShrink: 0,
                background: 'var(--ink)', color: '#fff', fontSize: 16,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                opacity: busy || !input.trim() ? 0.4 : 1,
                transition: 'opacity 150ms',
              }}>→</button>
          </div>
        </div>
      )}
    </>
  );
}

window.LandingAIAssistant = LandingAIAssistant;
