/* RIVA — Petite fenêtre de questions
   Les réponses viennent de ai-faq.jsx, calculées sur la carte réelle.
   Aucune connexion à un service extérieur, donc aucun coût et aucune
   donnée client qui sort du restaurant. */
const { useState: useAI, useEffect: useAIE, useRef: useAIR } = React;

const QUICK_SUGGESTIONS = [
  { icon: '🍕', text: "Comment composer une pizza sur mesure ?" },
  { icon: '🥙', text: "Comment composer mon panuozzo ?" },
  { icon: '🌶', text: "Quels plats sont épicés ?" },
  { icon: '🌱', text: "Vous avez une option végétarienne ?" },
  { icon: '⚠️', text: "Comment vérifier les allergènes ?" },
  { icon: '☪', text: "C'est halal ?" },
  { icon: '🕒', text: "Vous êtes ouverts quand ?" },
];

function AIChat({ open, onClose }) {
  const [messages, setMessages] = useAI([
    {
      role: 'assistant',
      content: 'Bonjour ! Je réponds à vos questions sur la carte de Riva : compositions, allergènes, horaires, livraison, ou un conseil si vous hésitez.',
    },
  ]);
  const [input, setInput] = useAI('');
  const [loading, setLoading] = useAI(false);
  const [error, setError] = useAI(null);
  const scrollRef = useAIR(null);
  const inputRef = useAIR(null);

  useAIE(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages, loading]);

  useAIE(() => {
    if (open && inputRef.current) {
      setTimeout(() => inputRef.current?.focus(), 200);
    }
  }, [open]);

  useAIE(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const send = async (text) => {
    const userMsg = (text || input).trim();
    if (!userMsg || loading) return;
    setInput('');
    setError(null);
    const newMessages = [...messages, { role: 'user', content: userMsg }];
    setMessages(newMessages);
    setLoading(true);

    // 1. Cherche d'abord dans la FAQ locale (instantané, gratuit, 100% offline)
    try {
      await new Promise(r => setTimeout(r, 400)); // léger délai pour effet "réflexion"
      const localAnswer = tryLocalFaq(userMsg);
      if (localAnswer) {
        setMessages([...newMessages, { role: 'assistant', content: localAnswer }]);
        setLoading(false);
        return;
      }

      // 2. Fallback : message poli si pas trouvé
      const fallback = `Je n'ai pas bien compris la question.

Je sais répondre sur :
• Un plat précis de la carte (tapez son nom)
• Les allergènes possibles (à confirmer avec l’équipe)
• Les pizzas et panuozzos à composer
• Halal, plats végétariens et plats épicés
• Horaires, livraison, à emporter, commande à table
• Les prix et les boissons

Reformulez${SHOP.phone ? `, ou appelez-nous au ${SHOP.phone}` : ', ou demandez directement au restaurant'}.`;
      setMessages([...newMessages, { role: 'assistant', content: fallback }]);
    } catch (e) {
      console.error(e);
      setMessages([...newMessages, {
        role: 'assistant',
        content: `Désolé, un souci technique.${SHOP.phone ? ` Appelez directement le restaurant au ${SHOP.phone}.` : ' Réessayez dans un instant.'}`,
      }]);
    } finally {
      setLoading(false);
    }
  };

  const handleKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      send();
    }
  };

  if (!open) return null;

  return (
    <>
      <div className="fixed inset-0 voile-fonce backdrop-blur-sm z-[180]" onClick={onClose}/>
      <div className="fixed inset-x-3 bottom-3 md:bottom-5 md:right-5 md:left-auto md:w-[400px] z-[190] bg-[var(--bg-2)] rounded-3xl border border-[var(--line)] flex flex-col overflow-hidden shadow-2xl"
           style={{ maxHeight: 'min(640px, calc(100vh - 80px))', height: 'min(640px, calc(100vh - 80px))' }}>

        {/* Header */}
        <div className="px-5 py-4 border-b border-[var(--line)] flex items-center gap-3 bg-gradient-to-r from-[var(--vert)]/10 to-transparent">
          <div className="relative">
            <div className="w-10 h-10 rounded-full bg-[var(--vert)] flex items-center justify-center">
              <svg viewBox="0 0 24 24" className="w-5 h-5 text-[var(--bg)]" fill="currentColor">
                <path d="M12 2C7 2 3 5.5 3 10c0 2 1 4 3 5l-1 4 4-2c.9.3 1.8.5 3 .5 5 0 9-3.5 9-8s-4-8-9-8z"/>
                <circle cx="9" cy="10" r="1" fill="var(--bg)"/>
                <circle cx="15" cy="10" r="1" fill="var(--bg)"/>
              </svg>
            </div>
            <div className="absolute -bottom-0.5 -right-0.5 w-3.5 h-3.5 bg-[var(--jade)] rounded-full border-2 border-[var(--bg-2)]"/>
          </div>
          <div className="flex-1 min-w-0">
            <div className="font-display text-lg leading-tight">Une question ?</div>
            <div className="text-[11px] text-[var(--jade)] flex items-center gap-1">
              <span className="w-1.5 h-1.5 rounded-full bg-[var(--jade)] pulse-dot"/>
              Réponse immédiate · sans attente
            </div>
          </div>
          <button onClick={onClose} className="w-9 h-9 rounded-full bg-[var(--bg)] flex items-center justify-center hover:bg-[var(--bg-3)]">
            <Icon.Close className="w-4 h-4"/>
          </button>
        </div>

        {/* Messages */}
        <div ref={scrollRef} className="flex-1 overflow-y-auto px-4 py-4 space-y-3">
          {messages.map((m, i) => (
            <Message key={i} role={m.role} content={m.content}/>
          ))}
          {loading && (
            <div className="flex gap-2">
              <div className="w-7 h-7 rounded-full bg-[var(--vert)] flex items-center justify-center shrink-0">
                <span className="text-xs">🥢</span>
              </div>
              <div className="bg-[var(--bg)] rounded-2xl rounded-tl-sm px-4 py-3 flex gap-1">
                <span className="w-1.5 h-1.5 rounded-full bg-[var(--muted)] animate-pulse" style={{animationDelay: '0ms'}}/>
                <span className="w-1.5 h-1.5 rounded-full bg-[var(--muted)] animate-pulse" style={{animationDelay: '200ms'}}/>
                <span className="w-1.5 h-1.5 rounded-full bg-[var(--muted)] animate-pulse" style={{animationDelay: '400ms'}}/>
              </div>
            </div>
          )}

          {messages.length === 1 && !loading && (
            <div className="pt-2">
              <div className="text-[11px] uppercase tracking-wider text-[var(--muted)] font-bold mb-2 px-1">Questions fréquentes</div>
              <div className="grid gap-1.5">
                {QUICK_SUGGESTIONS.map((s, i) => (
                  <button key={i} onClick={() => send(s.text)}
                          className="text-left bg-[var(--bg)] hover:bg-[var(--bg-3)] hover:border-[var(--vert)]/40 border border-[var(--line)] rounded-xl px-3 py-2.5 text-sm flex items-center gap-2.5 transition-colors">
                    <span className="text-base">{s.icon}</span>
                    <span className="text-[var(--cream-2)]">{s.text}</span>
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Input */}
        <div className="border-t border-[var(--line)] p-3 bg-[var(--bg)]/50">
          <div className="flex items-end gap-2 bg-[var(--bg)] rounded-2xl border border-[var(--line)] p-2 focus-within:border-[var(--vert)]/40 transition-colors">
            <textarea
              ref={inputRef}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={handleKey}
              placeholder="Posez votre question…"
              rows="1"
              className="flex-1 bg-transparent outline-none text-sm text-[var(--cream)] px-2 py-1.5 resize-none max-h-32"
              style={{ minHeight: '32px' }}
            />
            <button onClick={() => send()} disabled={!input.trim() || loading}
                    className="w-9 h-9 rounded-full bg-[var(--vert)] text-[var(--bg)] flex items-center justify-center disabled:opacity-40 hover:bg-[var(--vert-2)] transition-colors shrink-0">
              <svg viewBox="0 0 24 24" className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <line x1="22" y1="2" x2="11" y2="13"/>
                <polygon points="22 2 15 22 11 13 2 9 22 2"/>
              </svg>
            </button>
          </div>
          <div className="text-[10px] text-[var(--muted)] mt-1.5 px-2 text-center">
            Réponses calculées sur notre carte · rien ne sort du restaurant
          </div>
        </div>
      </div>
    </>
  );
}

function Message({ role, content }) {
  const isUser = role === 'user';
  // Clean markdown asterisks et autres formats markdown
  const clean = isUser ? content : content
    .replace(/\*\*([^*]+)\*\*/g, '$1')
    .replace(/__([^_]+)__/g, '$1')
    .replace(/\*([^*\n]+)\*/g, '$1')
    .replace(/_([^_\n]+)_/g, '$1')
    .replace(/^[\-\*]\s+/gm, '• ');
  return (
    <div className={`flex gap-2 ${isUser ? 'flex-row-reverse' : ''}`}>
      {!isUser && (
        <div className="w-7 h-7 rounded-full bg-[var(--vert)] flex items-center justify-center shrink-0 text-xs">
          🥢
        </div>
      )}
      <div className={`max-w-[85%] rounded-2xl px-4 py-2.5 text-sm leading-relaxed whitespace-pre-wrap
        ${isUser
          ? 'bg-[var(--vert)] text-[var(--bg)] rounded-tr-sm font-medium'
          : 'bg-[var(--bg)] text-[var(--cream-2)] rounded-tl-sm border border-[var(--line)]'}`}>
        {clean}
      </div>
    </div>
  );
}

// Floating launcher button
function AILauncher({ onOpen, hidden }) {
  const [bounce, setBounce] = useAI(false);
  useAIE(() => {
    const t = setTimeout(() => setBounce(true), 8000);
    const t2 = setTimeout(() => setBounce(false), 11000);
    return () => { clearTimeout(t); clearTimeout(t2); };
  }, []);
  if (hidden) return null;
  return (
    <button onClick={onOpen}
            className="fixed bottom-4 right-4 md:bottom-5 md:right-5 z-[80] group flex items-center gap-2 md:gap-3 p-1 md:pl-2 md:pr-4 md:py-2 rounded-full bg-[var(--vert)] text-[var(--bg)] shadow-2xl hover:bg-[var(--vert-2)] transition-all"
            style={{ boxShadow: '0 10px 32px rgba(201,165,78,0.32)' }}
            aria-label="Ouvrir la fenêtre de questions">
      <div className={`relative w-12 h-12 md:w-10 md:h-10 rounded-full bg-[var(--bg)] flex items-center justify-center ${bounce ? 'animate-bounce' : ''}`}>
        <svg viewBox="0 0 24 24" className="w-6 h-6 md:w-5 md:h-5 text-[var(--vert)]" fill="none" stroke="currentColor" strokeWidth="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"/>
          <circle cx="8.5" cy="11.5" r="1" fill="currentColor"/>
          <circle cx="12" cy="11.5" r="1" fill="currentColor"/>
          <circle cx="15.5" cy="11.5" r="1" fill="currentColor"/>
        </svg>
        <span className="absolute top-0.5 right-0.5 w-3 h-3 bg-[var(--jade)] rounded-full border-2 border-[var(--vert)] pulse-dot"/>
      </div>
      <div className="hidden md:block text-left pr-1">
        <div className="font-display text-sm leading-tight">Une question ?</div>
        <div className="text-[10px] uppercase tracking-wider font-bold opacity-70">Réponse immédiate</div>
      </div>
    </button>
  );
}

Object.assign(window, { AIChat, AILauncher, Message });
